public async Task Handle(OrderStockRejectedIntegrationEvent @event) { using (LogContext.PushProperty("IntegrationEventContext", $"{@event.Id}-{Program.AppName}")) { _logger.LogInformation("----- Handling integration event: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", @event.Id, Program.AppName, @event); var orderStockRejectedItems = @event.OrderStockItems .FindAll(c => !c.HasStock) .Select(c => c.ProductId) .ToList(); var command = new SetStockRejectedOrderStatusCommand(@event.OrderId, orderStockRejectedItems); _logger.LogInformation( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", command.GetGenericTypeName(), nameof(command.OrderNumber), command.OrderNumber, command); await _mediator.Send(command); } }
public override async Task <TResponse> UnaryServerHandler <TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod <TRequest, TResponse> continuation) { var correlationId = context .RequestHeaders .FirstOrDefault(h => h.Key.Equals("X-Correlation-ID", StringComparison.OrdinalIgnoreCase))?.Value; using (LogContext.PushProperty("X-Correlation-ID", correlationId)) { var sw = Stopwatch.StartNew(); var response = await base.UnaryServerHandler(request, context, continuation); sw.Stop(); Log.Logger.Information(MessageTemplate, context.Method, context.Status.StatusCode, sw.Elapsed.TotalMilliseconds); return(response); } }
public async Task Handle(UserFollowedEvent message, IMessageHandlerContext context) { using (LogContext.PushProperty("IntegrationEventContext", $"{message.Id}-{Program.AppName}")) { _logger.LogInformation("----- Handling UserFollowedEvent: {IntegrationEventId} at {AppName} - ({@IntegrationEvent})", message.Id, Program.AppName, message); var followCommand = new FollowCommand { FollowerId = message.FollowerId, FollowedUserId = message.FollowedUserId }; await _mediator.Send(followCommand); var fromUser = await _userRepository.GetByIdAsync(message.FollowerId); var eventCommand = new CreateEventCommand { FromUserId = message.FollowerId, ToUserId = message.FollowedUserId, EventType = EventType.Follow, PushMessage = $"{fromUser.Nickname}开始关注你" }; await _mediator.Send(eventCommand); } }
public void DoesNotPreventCrossDomainCalls() { AppDomain domain = null; try { domain = AppDomain.CreateDomain("LogContextTests", null, AppDomain.CurrentDomain.SetupInformation); // ReSharper disable AssignNullToNotNullAttribute var callable = (RemotelyCallable)domain.CreateInstanceAndUnwrap(typeof(RemotelyCallable).Assembly.FullName, typeof(RemotelyCallable).FullName); // ReSharper restore AssignNullToNotNullAttribute using (LogContext.PushProperty("Anything", 1001)) Assert.True(callable.IsCallable()); } finally { if (domain != null) { AppDomain.Unload(domain); } } }
public string Home() { // Use LogContext to automatically enrich all log entries written within // a block of code with contextual properties. using (LogContext.PushProperty("requestMethod", Request.Method)) using (LogContext.PushProperty("requestUrl", Request.GetDisplayUrl())) { logger.Information("This is a .NET example of structured logging for customer ID {customerId}.", 42); logger.Warning("Ooooo, this is a warning! (from .NET)"); try { var foo = new Foo(); foo.Crash(); } catch (Exception e) { logger.Error(e, "Look: An intentional error. (from .NET)"); } return("Hello, World. I'm a .NET Core app. \n\nView my logs at https://console.cloud.google.com/logs/viewer?advancedFilter=dotnetlogdemo \n\nView my errors at https://console.cloud.google.com/errors"); } }
public override async Task <HttpResponse> InvokeAsync(HttpRequest request) { using var _ = LogContext.PushProperty("RequestId", request.RequestId); var sw = Stopwatch.StartNew(); try { var response = await _next.InvokeAsync(request); LogCompletion(null, request, sw, response.StatusCode); return(response); } catch (Exception ex1) when(LogCompletion(ex1, request, sw, HttpStatusCode.InternalServerError)) { // We never hit this, because the exception filter always returns false. throw; } catch { return(new HttpResponse(HttpStatusCode.InternalServerError, "An error occurred.")); } }
/// <summary> /// Create a new test-suite. /// </summary> /// <param name="testOutput"> /// Output for the current test. /// </param> protected TestBase(ITestOutputHelper testOutput) { if (testOutput == null) { throw new ArgumentNullException(nameof(testOutput)); } // We *must* have a synchronisation context for the test, or we'll see random deadlocks. SynchronizationContext.SetSynchronizationContext( new SynchronizationContext() ); TestOutput = testOutput; // Redirect component logging to Serilog. Log = new LoggerConfiguration() .MinimumLevel.Verbose() .Enrich.FromLogContext() .WriteTo.Debug( restrictedToMinimumLevel: LogEventLevel.Verbose ) .WriteTo.TestOutput(TestOutput, LogLevelSwitch) .CreateLogger(); // Ugly hack to get access to the current test. CurrentTest = (ITest) TestOutput.GetType() .GetField("test", BindingFlags.NonPublic | BindingFlags.Instance) .GetValue(TestOutput); Assert.True(CurrentTest != null, "Cannot retrieve current test from ITestOutputHelper."); Disposal.Add( LogContext.PushProperty("TestName", CurrentTest.DisplayName) ); }
private void HandleIdentifyController(clsOmniLinkMessageQueueItem M, byte[] B, bool Timeout) { if (Timeout) { return; } if ((B.Length > 3) && (B[2] == (byte)enuOmniLink2MessageType.SystemInformation)) { clsOL2MsgSystemInformation MSG = new clsOL2MsgSystemInformation(Controller.Connection, B); foreach (enuModel enu in Enum.GetValues(typeof(enuModel))) { if (enu == MSG.ModelNumber) { Controller.Model = enu; break; } } if (Controller.Model == MSG.ModelNumber) { Controller.CopySystemInformation(MSG); using (LogContext.PushProperty("Telemetry", "Controller")) log.Information("Controller is {ControllerModel} firmware {ControllerVersion}", Controller.GetModelText(), Controller.GetVersionText()); _ = Connected(); return; } log.Error("Model does not match file"); Controller.Connection.Disconnect(); } }
public async void CheckPurchaseFinTest() { LogContext.PushProperty("TestFunction", "CheckPurchaseFinTest"); _Logger.Information("Start CheckPurchaseFinTest"); Application.Model.Procurment.Purchase _purchase = _dbContext.Purchase.FirstOrDefault(); UpdateMovementStatusCommand _updatePurchaseStatusCommand = new UpdateMovementStatusCommand { Id = _purchase.Id, SenderId = 0, PurchaseDetailId = null, PurchaseAction = PurchaseAction.paQtyPost }; var result = await _mediator.Send(_updatePurchaseStatusCommand); UpdateMovementStatusCommand _updatePurchaseStatusCommand1 = new UpdateMovementStatusCommand { Id = _purchase.Id, SenderId = 0, PurchaseDetailId = null, PurchaseAction = PurchaseAction.paCostPost }; var result1 = await _mediator.Send(_updatePurchaseStatusCommand1); await _dbContext.SaveChangesAsync(CancellationToken.None); _Logger.Information("End CheckPurchaseFinTest"); var i = await _dbContext.Inventory.ToListAsync(); var ic = await _dbContext.InventoryChange.ToListAsync(); Assert.Equal(6, i.Count()); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var response = default(TResponse); var typeName = request.GetType().ToString(); try { var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { Guid transactionId; using (var transaction = await _dbContext.BeginTransactionAsync()) using (LogContext.PushProperty("TransactionContext", transaction.TransactionId)) { _logger.LogInformation("----- Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, request); response = await next(); _logger.LogInformation("----- Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); await _dbContext.CommitTransactionAsync(transaction); transactionId = transaction.TransactionId; } }); return(response); } catch (Exception ex) { _logger.LogError(ex, "ERROR Handling transaction for {CommandName} ({@Command})", typeName, request); _dbContext.RollbackTransaction(); throw; } }
public static void Main() { SetupLogglyConfiguration(); using (var logger = CreateLogger(@"C:\test\Logs\")) { logger.Information("Test message - app started"); logger.Warning("Test message with {@Data}", new { P1 = "sample", P2 = DateTime.Now }); logger.Warning("Test2 message with {@Data}", new { P1 = "sample2", P2 = 10 }); Console.WriteLine( "Disconnect to test offline. Two messages will be sent. Press enter to send and wait a minute or so before reconnecting or use breakpoints to see that send fails."); Console.ReadLine(); logger.Information("Second test message"); logger.Warning("Second test message with {@Data}", new { P1 = "sample2", P2 = DateTime.Now, P3 = DateTime.UtcNow, P4 = DateTimeOffset.Now, P5 = DateTimeOffset.UtcNow }); Console.WriteLine( "Offline messages written. Once you have confirmed that messages have been written locally, reconnect to see messages go out. Press Enter for more messages to be written."); Console.ReadLine(); logger.Information("Third test message"); logger.Warning("Third test message with {@Data}", new { P1 = "sample3", P2 = DateTime.Now }); Console.WriteLine( "Back online messages written. Check loggly and files for data. Wait a minute or so before reconnecting. Press Enter to continue"); Console.ReadLine(); using (LogContext.PushProperty("sampleProperty", "Sample Value")) { logger.Information("message to send with {@Data}", new { P1 = "sample4", P2 = DateTime.Now }); } Console.WriteLine( "Pushed property added to object. Check loggly and data. Press Enter to terminate"); Console.ReadLine(); } }
static void Main(string[] args) { var application = "csharp-serilog-http/1.0"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.WithProperty("Application", application) .Enrich.FromLogContext() .WriteTo.Http("http://localhost:8080/serilog") .CreateLogger(); var log = Log.ForContext <Program>(); log.Information("Begin"); var traceId = Guid.NewGuid().ToString("N"); using (LogContext.PushProperty("TraceId", traceId)) { var a = 10; var b = 0; try { log.Debug("Dividing {A} by {B}", a, b); Console.WriteLine(a / b); } catch (Exception ex) { log.Error(ex, "Something went wrong with the division"); } } log.Information("End"); Log.CloseAndFlush(); }
public virtual async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var response = default(TResponse); var typeName = request.GetGenericTypeName(); try { if (_dbContext.HasActiveTransaction) { return(await next()); } var strategy = _dbContext.Database.CreateExecutionStrategy(); await strategy.ExecuteAsync(async() => { using (var transaction = await _dbContext.BeginTransactionAsync()) using (LogContext.PushProperty("TransactionContext", transaction.TransactionId)) { _logger.LogInformation("Begin transaction {TransactionId} for {CommandName} ({@Command})", transaction.TransactionId, typeName, request); response = await next(); _logger.LogInformation("Commit transaction {TransactionId} for {CommandName}", transaction.TransactionId, typeName); await _dbContext.CommitTransactionAsync(transaction); } }); return(response); } catch (Exception ex) { _logger.LogError(ex, "Error handling transaction for {CommandName} ({@Command})", typeName, request); throw; } }
/// <summary> /// Handle an inbound connection /// </summary> /// <param name="context">The context for the connection to handle</param> private async Task HandleConnectionAsync(HttpListenerContext context) { try { switch (context.Request.RawUrl) { case "/blocks": HandleBlocksRequest(context); break; case "/mineblock": MineBlock(context); break; case "/addpeer": await AddPeerAsync(context); break; case "/getpeers": await GetPeersAsync(context); break; } } catch (Exception exception) { using (LogContext.PushProperty("Request", context.Request, true)) { _logger.Error(exception, "An error occured while handling web request"); } } finally { context.Response.OutputStream.Close(); } }
public async Task <IActionResult> ResponseReady([FromBody] SearchResponseReady searchResponseReady) { using (LogContext.PushProperty("RequestRef", $"{searchResponseReady?.AgencyFileId}")) using (LogContext.PushProperty("AgencyCode", $"{searchResponseReady?.Agency}")) { _logger.LogInformation("Get searchResponseReady"); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { Person p = await _agencyResponseService.GetSearchRequestResponse(searchResponseReady); if (p == null) { return(BadRequest("wrong response guid")); } await _agencyNotifier.SendNotificationAsync( BuildSearchRequestNotification(searchResponseReady, p), (new CancellationTokenSource()).Token ); await _register.RegisterResponseApiCall(searchResponseReady); return(Ok()); } catch (Exception e) { _logger.LogError(e.Message); return(StatusCode(StatusCodes.Status500InternalServerError, new { Message = e.Message })); } } }
public async Task Run(DiscordRequest request, Contexts contexts) { if (this._controllersContainer == null) { this.LoadControllers(); } using (LogContext.PushProperty("MessageId", Guid.NewGuid())) using (LogContext.PushProperty("Request", request)) using (LogContext.PushProperty("Contexts", contexts)) { var readAlwaysMethods = this._controllersContainer.WithReadAlways; var readAlwaysTask = Task.Run(() => RunMethods(request, contexts, readAlwaysMethods, true)); Task commandsTask = null; Task botCommandsTask = null; if (request.IsCommandForBot) { var discordCommandMethods = this._controllersContainer.WithDiscordCommand; commandsTask = Task.Run(() => RunMethods(request, contexts, discordCommandMethods, false)); var discordBotCommandMethods = this._controllersContainer.WithIBotCommand; botCommandsTask = Task.Run(() => RunMethodsIBotCommand(request, contexts, discordBotCommandMethods, false)); } // ReadAlwaysMethods should be first in throwing exception, bcs every ReadAlways exception is Error await readAlwaysTask; if (commandsTask != null) { await commandsTask; } if (botCommandsTask != null) { await botCommandsTask; } } }
protected override async Task ExecuteAsync(CancellationToken token) { using (LogContext.PushProperty("TimedService", typeof(T).Name)) { Log.Information("Timed service {TimedService} registered", typeof(T).Name); while (!token.IsCancellationRequested) { using (var scope = _services.CreateScope()) { var service = scope.ServiceProvider.GetService <T>(); _interval = service.Interval; try { Log.Information("{TimedService} started running", typeof(T).Name); Stopwatch watch = Stopwatch.StartNew(); await service.Execute(); watch.Stop(); Log.Information("{TimedService} finished execution in {Elapsed} ms", typeof(T).Name, watch.ElapsedMilliseconds); _interval = service.Interval; } catch (Exception ex) { Log.Error(ex, "Failed during execution of timed service {TimedService}", typeof(T).Name); } } await Task.Delay(_interval, token); } } }
public async Task Execute(IJobExecutionContext context) { _logger.LogInformation("Search Request started!"); var cts = new CancellationTokenSource(); try { List <SSG_SearchApiRequest> requestList = await GetAllReadyForSearchAsync(cts.Token); foreach (SSG_SearchApiRequest ssgSearchRequest in requestList) { if (ssgSearchRequest.SearchRequestId != Guid.Empty) { using (LogContext.PushProperty("FileId", " - FileId: " + ssgSearchRequest.SearchRequest?.FileId)) { _logger.LogDebug( $"Attempting to post person search for request {ssgSearchRequest.SearchApiRequestId}"); var result = await _searchApiClient.SearchAsync( _mapper.Map <PersonSearchRequest>(ssgSearchRequest), $"{ssgSearchRequest.SearchApiRequestId}", cts.Token); _logger.LogInformation($"Successfully posted person search id:{result.Id}"); await MarkInProgress(ssgSearchRequest, cts.Token); } } } } catch (Exception e) { _logger.LogError(e, e.Message, null); } }
/// <inheritdoc /> public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { if (request is IBotActionRequest botRequest) { var update = botRequest.Update; var bot = await _botUserProvider.GetAsync(cancellationToken); var traceId = Guid.NewGuid().ToString(); _botContextAccessor.Context = new BotActionContext { Update = update, TraceId = traceId, Bot = bot }; using (LogContext.PushProperty("TraceId", traceId)) { return(await next()); } } return(await next()); }
private void LogHttpRequest(HttpContext context, double elapsedMs, Exception ex) { HttpResponse response = context.Response; using (LogContext.PushProperty(LogPropertyNames.SOURCE_IP, context.Connection.RemoteIpAddress)) using (LogContext.PushProperty(LogPropertyNames.HTTP_METHOD, context.Request.Method)) using (LogContext.PushProperty(LogPropertyNames.HTTP_REQUEST_URL, context.Request.Path.Value)) using (LogContext.PushProperty(LogPropertyNames.HTTP_PROTOCOL_VERSION, context.Request.Protocol)) using (LogContext.PushProperty(LogPropertyNames.HTTP_RESPONSE_STATUS_CODE, context.Response.StatusCode)) using (LogContext.PushProperty(LogPropertyNames.HTTP_RESPONSE_LENGTH, response.ContentLength ?? context.Response.Body.Length)) using (LogContext.PushProperty(LogPropertyNames.TIME_ZONE, timeZone_)) using (LogContext.PushProperty(LogPropertyNames.ELAPSED_MS, elapsedMs)) { if (ex != null) { logger_.LogError(ex, ""); //Properties cover all information, so empty message } else { logger_.LogInformation(""); //Properties cover all information, so empty message } } context.Response.Body.Position = 0; }
public static AppFunc Inject(AppFunc next) { return(async env => { var owinContext = new OwinContext(env); //initialize to unknown var subject = "unknown"; //if the subject id comes in the header set it from there if (owinContext.Request.Headers.ContainsKey(Constants.FabricHeaders.SubjectNameHeader)) { subject = owinContext.Request.Headers[Constants.FabricHeaders.SubjectNameHeader]; } //otherwise try to get it from the current user else if (owinContext.Request.User?.FindFirst(SubClaim) != null) { subject = owinContext.Request.User.FindFirst(SubClaim).Value; } owinContext.Set(Constants.FabricHeaders.SubjectNameHeader, subject); using (LogContext.PushProperty(Constants.FabricHeaders.SubjectNameHeader, subject)) { await next(env); } }); }
/// <summary> /// This method is called for every Lambda invocation. This method takes in an SQS event object and can be used /// to respond to SQS messages. /// </summary> /// <param name="evnt"></param> /// <param name="context"></param> /// <returns></returns> public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context) { context.Logger.LogLine($"Processed message using Serilog/Nlog"); var levelSwitch = new LoggingLevelSwitch(); levelSwitch.MinimumLevel = LogEventLevel.Warning; var logger = new LoggerConfiguration().Enrich.FromLogContext() .MinimumLevel.ControlledBy(levelSwitch).WriteTo.Console(new RenderedCompactJsonFormatter()).CreateLogger(); using (LogContext.PushProperty("level", "debug")) { logger.Debug("This is a debug level message"); } using (LogContext.PushProperty("level", "info")) { logger.Information("This is a info level message"); } using (LogContext.PushProperty("level", "warning")) { logger.Warning("This is a warning level message"); } using (LogContext.PushProperty("level", "error")) { logger.Error("Serilog Check the AWS Console CloudWatch Logs console"); } // TODO: Do interesting work based on the new message await Task.CompletedTask; }
public static AppFunc Middleware(AppFunc next) { return(async env => { var owinContext = new OwinContext(env); // Tries to find a correlation token in the request header if (!(owinContext.Request.Headers["Correlation-Token"] != null && Guid.TryParse(owinContext.Request.Headers["Correlation-Token"], out Guid correlationToken))) { // not found, creating a new one correlationToken = Guid.NewGuid(); } // Saves the correlation token for later use // e.g. adding correlation token for outgoing requests to other uservices owinContext.Set("correlationToken", correlationToken.ToString()); // Adds the correlation token to the log context using (LogContext.PushProperty("CorrelationToken", correlationToken)) { await next(env).ConfigureAwait(false); } }); }
private static async Task AsyncC(int i) { await Task.Delay(50); Log.Logger.Information("Sync C = {@i}", i); Task a = Task.Run(async() => { using (LogContext.PushProperty("PCId", _customContext.Value)) //Guid.NewGuid())) { int id = Interlocked.Increment(ref _counter); _customContext.Value = id; _customContextFlow.Value = _customContextFlow.Value.Add(id); using (LogContext.PushProperty("CIds", _customContextFlow.Value)) //Guid.NewGuid())) using (LogContext.PushProperty("CId", id)) //Guid.NewGuid())) { await AsyncD1(i, 'A'); } } }); Task b = Task.Run(async() => { using (LogContext.PushProperty("PCId", _customContext.Value)) //Guid.NewGuid())) { int id = Interlocked.Increment(ref _counter); _customContext.Value = id; _customContextFlow.Value = _customContextFlow.Value.Add(id); using (LogContext.PushProperty("CIds", _customContextFlow.Value)) //Guid.NewGuid())) using (LogContext.PushProperty("CId", id)) //Guid.NewGuid())) { await AsyncD1(i, 'B'); } } }); await Task.WhenAll(a, b); }
public async Task Invoke(HttpContext context) { string correlationId; if (context.Request.Headers.TryGetValue( CorrelationIdHeaderName, out StringValues correlationIdHeaderValues)) { correlationId = string.Join(";", correlationIdHeaderValues.ToArray()); } else { correlationId = context.TraceIdentifier; } context.Response.OnStarting( state => { var httpContext = (HttpContext)state; httpContext.Response.Headers.Append( RequestIdHeaderName, context.TraceIdentifier); httpContext.Response.Headers.Append( CorrelationIdHeaderName, correlationId); return(Task.FromResult(0)); }, context); using (LogContext.PushProperty(CorrelationIdPropertyName, correlationId)) { await this.next(context); } }
/// <summary> /// Consumes the specified message from the bus. /// </summary> /// <param name="context">The context from the bus.</param> /// <returns>Task.</returns> public async Task Consume(ConsumeContext <IArchiveRecordUpdated> context) { using (LogContext.PushProperty(nameof(context.ConversationId), context.ConversationId)) { Log.Information("Received {CommandName} event with conversationId {ConversationId} from the bus", nameof(IArchiveRecordUpdated), context.ConversationId); // Nur wenn die VE erfolgreich aktualisiert worden ist, prüfen wir, ob es zur VE Einträge in der WaitList hat. // In der Regel sollte nur ein Wert zurück geliefert werden.- // Wenn ja, dann rufen wir erneut die DigitalisierungsAuftragErledigtEvent auf. Dieser löst dann den Download aus. if (context.Message.ActionSuccessful) { var items = await orderDataAccess.GetVeFromOrderExecutedWaitList(context.Message.ArchiveRecordId); foreach (var item in items) { var message = JsonConvert.DeserializeObject <DigitalisierungsAuftragErledigt>(item.SerializedMessage); var ep = await context.GetSendEndpoint(new Uri(bus.Address, BusConstants.DigitalisierungsAuftragErledigtEvent)); await ep.Send <IDigitalisierungsAuftragErledigt>(new { message.ArchiveRecordId, message.OrderItemId, message.OrderDate, message.OrderUserId, message.OrderUserRolePublicClient }); Log.Information("Sent {IDigitalisierungsAuftragErledigt} message on bus from ArchiveRecordUpdatedConsumer", nameof(IDigitalisierungsAuftragErledigt)); await orderDataAccess.MarkOrderAsProcessedInWaitList(item.OrderExecutedWaitListId); } } } }
private async Task TryConnectAndAuthenticate() { if (!_authenticated) { using (LogContext.PushProperty("Server", _ipEndPoint.ToString())) { _logger.LogDebug("Authenticating to RCon socket"); } await _rconClient.ConnectAsync().WithTimeout(ConnectionTimeout); _authenticated = await _rconClient.AuthenticateAsync(_password).WithTimeout(ConnectionTimeout); if (!_authenticated) { using (LogContext.PushProperty("Server", _ipEndPoint.ToString())) { _logger.LogError("Could not login to server"); } throw new ServerException("Could not authenticate to server with provided password"); } } }
protected virtual async Task OnInitiativeWorkItemCreated(WorkOrderCreatedEventArgs args, CancellationToken token) { if (args == null) { throw new ArgumentNullException("args"); } if (args.Initiative == null) { throw new ArgumentException("Initiative cannot be null"); } if (string.IsNullOrWhiteSpace(args.WorkOrderId)) { throw new ArgumentException("WorkOrderId cannot be empty"); } using (LogContext.PushProperty("InitiativeId", args.Initiative.Id)) { _logger.Information("Remedy has created a work item for initiative {InitiativeId} with remedy id {WorkOrderId}", args.Initiative.Id, args.WorkOrderId); try { args.Initiative.SetWorkOrderId(args.WorkOrderId); args.Initiative.UpdateStatus(InitiativeStatus.Submit, args.EtaUtc); _logger.Information("Saving Initiative {InitiativeId} to database", args.Initiative.Id); await _ideaRepository.UpdateInitiativeAsync(args.Initiative); } catch (Exception err) { _logger.Error(err, "Unable to set work item id '{WorkOrderId}' to initiative id {InitiativeId}. Will retry later. Error was: {ErrorMessage}", args.WorkOrderId, args.Initiative.Id, err.Message); throw; } } }
/// <summary> /// Send a message to a particular players /// </summary> /// <param name="message">Message to send</param> /// <param name="targetClient">EFClient to send message to</param> protected async Task Tell(string message, EFClient targetClient) { var engineMessage = message.FormatMessageForEngine(RconParser.Configuration.ColorCodeMapping); if (!Utilities.IsDevelopment) { var temporalClientId = targetClient.GetAdditionalProperty <string>("ConnectionClientId"); var parsedClientId = string.IsNullOrEmpty(temporalClientId) ? (int?)null : int.Parse(temporalClientId); var clientNumber = parsedClientId ?? targetClient.ClientNumber; var formattedMessage = string.Format(RconParser.Configuration.CommandPrefixes.Tell, clientNumber, $"{(CustomSayEnabled && GameName == Game.IW4 ? $"{CustomSayName}: " : "")}{engineMessage}"); if (targetClient.ClientNumber > -1 && message.Length > 0 && targetClient.Level != EFClient.Permission.Console) { await this.ExecuteCommandAsync(formattedMessage); } } else { ServerLogger.LogDebug("Tell[{ClientNumber}]->{Message}", targetClient.ClientNumber, message.FormatMessageForEngine(RconParser.Configuration.ColorCodeMapping).StripColors()); } if (targetClient.Level == EFClient.Permission.Console) { Console.ForegroundColor = ConsoleColor.Green; using (LogContext.PushProperty("Server", ToString())) { ServerLogger.LogInformation("Command output received: {Message}", engineMessage.StripColors()); } Console.WriteLine(engineMessage.StripColors()); Console.ForegroundColor = ConsoleColor.Gray; } }
private LogActive LogMethodBeforeInvocation(IInvocation invocation, LogActive activeState) { if (invocation == null) { throw new ArgumentNullException(nameof(invocation)); } LogActive methodActiveState = activeState; MethodInfo methodInfo = invocation.MethodInvocationTarget; Debug.Assert(methodInfo != null); // Check for DiagnosticLogging Method scope. var methodDiagnosticAttribute = methodInfo .GetCustomAttribute(typeof(DiagnosticLoggingAttribute), false) as DiagnosticLoggingAttribute; if (methodDiagnosticAttribute != null) { methodActiveState = methodDiagnosticAttribute.LogActive; } (IList <object> filteredParameters, LogActive anyParametersToLog) = FilterParameters(invocation, methodInfo, methodActiveState, m_FilterTheseParameters); if (anyParametersToLog == LogActive.On) { using (LogContext.PushProperty(LogTypeName, LogType.Diagnostic)) using (LogContext.Push(new InvocationEnricher(invocation))) using (LogContext.PushProperty(ArgumentsName, filteredParameters, destructureObjects: true)) { string logMessage = $"{GetSourceMessage(invocation)} invocation started"; m_Logger.Information(logMessage); } } return(methodActiveState); }