Exemplo n.º 1
0
 /// <summary>
 /// Set enricher
 /// </summary>
 /// <param name="enricher"></param>
 public void SetEnricher(ILogEventEnricher enricher)
 {
     if (enricher != null)
     {
         LogEventEnricherManager.UpdateEnricher(enricher);
     }
 }
Exemplo n.º 2
0
 public async Task Invoke(HttpContext context, ILogEventEnricher logEventEnricher)
 {
     using (LogContext.Push(logEventEnricher))
     {
         await _next(context);
     }
 }
Exemplo n.º 3
0
        public ILogger ForContext(ILogEventEnricher enricher)
        {
            if (enricher == null)
            {
                return(this);
            }

            if (_frozen)
            {
                return(_cached.ForContext(enricher));
            }

            if (_reloadableLogger.CreateChild(
                    _root,
                    this,
                    _cached,
                    p => p.ForContext(enricher),
                    out var child,
                    out var newRoot,
                    out var newCached,
                    out var frozen))
            {
                Update(newRoot, newCached, frozen);
            }

            return(child);
        }
Exemplo n.º 4
0
 internal Logger(
     LoggingLevelSwitch levelSwitch,
     ILogEventSink sink,
     ILogEventEnricher enricher,
     Action dispose = null,
     LevelOverrideMap overrideMap = null)
     : this(sink, enricher, dispose, levelSwitch, overrideMap)
 {
 }
Exemplo n.º 5
0
        public Logger(ILogEventEnricher enricher)
        {
            if (enricher is null)
            {
                throw new ArgumentNullException(nameof(enricher));
            }

            logger = new LoggerConfiguration().WriteTo.Console(outputTemplate: ConsoleTemplate).Enrich.With(enricher).Enrich.With(new ActivityEnrich()).CreateLogger();
        }
Exemplo n.º 6
0
        internal static void UpdateEnricher(ILogEventEnricher enricher)
        {
            if (enricher == null)
            {
                throw new ArgumentNullException(nameof(enricher));
            }

            _enrichers.Add(enricher);
        }
Exemplo n.º 7
0
        public ILogEventEnricher[] CreateAllEnrichers()
        {
            var enrichersList = new ILogEventEnricher[]
            {
                new ThreadIdEnricher(),
                new EnvironmentEnricher(this._config)
            };

            return(enrichersList);
        }
Exemplo n.º 8
0
        internal static string Resolve(ILogEventEnricher enricher)
        {
            var key = enricher.GetType().Name;

            if (_values.ContainsKey(key))
            {
                return(_values[key]());
            }
            return(null);
        }
        private static ILogEventEnricher[] GetEnrichers()
        {
            var enrichers = new ILogEventEnricher[]
            {
                new MachineNameEnricher(),
                new PropertyEnricher("ApplicationName", ConfigurationManager.AppSettings["Application.Name"]),
                new PropertyEnricher("Environment", ConfigurationManager.AppSettings["Environment"])
            };

            return(enrichers);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Create a logger that enriches log events via the provided enrichers.
 /// </summary>
 /// <param name="enricher">Enricher that applies in the context.</param>
 /// <returns>A logger that will enrich log events as specified.</returns>
 public Logger ForContext(ILogEventEnricher enricher)
 {
     if (enricher == null)
     {
         return(this); // No context here, so little point writing to SelfLog.
     }
     return(new Logger(
                this,
                enricher,
                null,
                _levelSwitch,
                _overrideMap));
 }
Exemplo n.º 11
0
 // The messageTemplateProcessor, sink and enricher are required. Argument checks are dropped because
 // throwing from here breaks the logger's no-throw contract, and callers are all in this file anyway.
 Logger(
     ILogEventSink sink,
     ILogEventEnricher enricher,
     Action dispose = null,
     LoggingLevelSwitch levelSwitch = null,
     LevelOverrideMap overrideMap   = null)
 {
     _sink        = sink;
     _dispose     = dispose;
     _levelSwitch = levelSwitch;
     _overrideMap = overrideMap;
     _enricher    = enricher;
 }
Exemplo n.º 12
0
        /// <summary>
        /// Push an enricher onto the context, returning an <see cref="IDisposable"/>
        /// that must later be used to remove the property, along with any others that
        /// may have been pushed on top of it and not yet popped. The property must
        /// be popped from the same thread/logical call context.
        /// </summary>
        /// <param name="enricher">An enricher to push onto the log context</param>
        /// <returns>A token that must be disposed, in order, to pop properties back off the stack.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IDisposable Push(ILogEventEnricher enricher)
        {
            if (enricher == null)
            {
                throw new ArgumentNullException(nameof(enricher));
            }

            var stack    = GetOrCreateEnricherStack();
            var bookmark = new ContextStackBookmark(stack);

            Enrichers = stack.Push(enricher);

            return(bookmark);
        }
        public ILogger ForContext(ILogEventEnricher enricher)
        {
            if (enricher == null)
            {
                return(this);
            }

            if (_frozen)
            {
                return(_cached.ForContext(enricher));
            }

            return(new CachingReloadableLogger(_reloadableLogger, _root, this, p => p.ForContext(enricher)));
        }
Exemplo n.º 14
0
        public ILogger ForContext(ILogEventEnricher enricher)
        {
            if (enricher == null)
            {
                return(this);
            }

            if (_frozen)
            {
                return(_logger.ForContext(enricher));
            }

            lock (_sync)
                return(new CachingReloadableLogger(this, _logger, this, p => p.ForContext(enricher)));
        }
Exemplo n.º 15
0
        public async Task <T> Send <T>(IRequest <T> command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }
            var meta = new Metadata
            {
                AccessToken = _metadata.AccessToken,
                TraceId     = Guid.NewGuid().ToString()
            };
            var envelope = new MessageEnvelope
            {
                Meta    = meta,
                Payload = command
            };
            var diagnosticProperties = new ILogEventEnricher[]
            {
                new PropertyEnricher("ConnectionId", _hubConnection.ConnectionId),
                new PropertyEnricher("TraceId", meta.TraceId),
                new PropertyEnricher("CommandType", command.GetType().Name)
            };

            using (LogContext.Push(diagnosticProperties))
            {
                var result = await _retryPolicy.ExecuteAsync(async() =>
                {
                    try
                    {
                        using (_logger.BeginTimedOperation(OperationDescription))
                        {
                            return(await SendInternal <T>(envelope));
                        }
                    }
                    catch (Exception ex)
                    {
                        var level = ex is UserException ? LogEventLevel.Warning : LogEventLevel.Error;
                        _logger.Write(level, ex, "[SignalRClient:{ConnectionId}:{TraceId}] {ErrorMessage}",
                                      _hubConnection.ConnectionId,
                                      envelope.Meta.TraceId,
                                      ex.Message);
                        throw;
                    }
                });

                return(result);
            }
        }
Exemplo n.º 16
0
        public void User_Enricher_should_add_the_correct_user_id_property(string userID, string userName)
        {
            var enrichers = new ILogEventEnricher[]
            {
                new UserEnricher(new Enrichers.UserEnrichment()
                {
                    GetUserID   = () => userID,
                    GetUserName = () => userName
                })
            };

            Logging.InitializeLogging(_config, enrichers, _sinks);

            using (TestCorrelator.CreateContext())
            {
                Log.Error("Test Error");
                TestCorrelator.GetLogEventsFromCurrentContext().ShouldHaveSingleItem().Properties["UserID"].ToString().Replace("\"", string.Empty).ShouldBe(userID);
            }
        }
Exemplo n.º 17
0
        public void User_Enricher_should_add_two_properties_with_expected_keys(string userID, string userName)
        {
            var enrichers = new ILogEventEnricher[]
            {
                new UserEnricher(new Enrichers.UserEnrichment()
                {
                    GetUserID   = () => userID,
                    GetUserName = () => userName
                })
            };

            Logging.InitializeLogging(_config, enrichers, _sinks);

            using (TestCorrelator.CreateContext())
            {
                Log.Error("Test Error");
                TestCorrelator.GetLogEventsFromCurrentContext().ShouldHaveSingleItem().Properties.Keys.ShouldContain("UserName", "UserID");
            }
        }
Exemplo n.º 18
0
        public override Task OnDisconnected(bool stopCalled)
        {
            var props = new ILogEventEnricher[]
            {
                new PropertyEnricher("ConnectionId", Context.ConnectionId),
                new PropertyEnricher("StopCalled", stopCalled)
            };

            using (LogContext.Push(props))
            {
                var removed = Connections.TryRemove(Context.ConnectionId, out GameHubConnection hubConnection);
                if (!removed)
                {
                    return(Task.CompletedTask);
                }
                _connectionsGauge.Write();
                hubConnection.Dispose();
                return(base.OnDisconnected(stopCalled));
            }
        }
Exemplo n.º 19
0
        public async Task <TResponse> Handle(CommandEnvelope <TCommand, TResponse> message,
                                             RequestHandlerDelegate <TResponse> next)
        {
            var context = message.Context;
            var diagnosticProperties = new ILogEventEnricher[]
            {
                new PropertyEnricher("TraceId", context.Metadata.TraceId),
                new PropertyEnricher("UserId", context.UserId),
                new PropertyEnricher("ConnectionId", context.Connection.Id),
                new PropertyEnricher("CommandType", message.Command.GetType().Name)
            };

            using (LogContext.Push(diagnosticProperties))
            {
                try
                {
                    _received.Increment();
                    _logger.Debug("[Handler:{TraceId}:{UserId}] Received {CommandType}: {@Command}",
                                  context.Metadata.TraceId,
                                  context.UserId,
                                  message.Command.GetType().Name,
                                  message.Command);
                    TResponse response;
                    using (_logger.BeginTimedOperation(OperationDescription))
                    {
                        response = await next.Invoke();
                    }
                    _logger.Debug("[Handler:{TraceId}:{UserId}] Handled {CommandType} successfully: {@Response}",
                                  context.Metadata.TraceId,
                                  context.UserId,
                                  message.Command.GetType().Name,
                                  response);
                    return(response);
                }
                finally
                {
                    _processed.Increment();
                }
            }
        }
        public async Task Invoke(HttpContext httpContext)
        {
            var bodyStream = httpContext.Response.Body;

            var responseBodyStream = new MemoryStream();

            try
            {
                httpContext.Response.Body = responseBodyStream;

                await _next(httpContext);

                if (httpContext.Response?.StatusCode > 399)
                {
                    responseBodyStream.Seek(0, SeekOrigin.Begin);
                    var reader          = new StreamReader(responseBodyStream);
                    var responseContent = await reader.ReadToEndAsync();

                    var enrichers = new ILogEventEnricher[]
                    {
                        new PropertyEnricher(nameof(httpContext.Response.ContentType), httpContext.Response.ContentType),
                        new PropertyEnricher(nameof(httpContext.Response.StatusCode), httpContext.Response.StatusCode),
                        new PropertyEnricher("ResponseContent", responseContent)
                    };
                    using (LogContext.Push(enrichers))
                    {
                        Logger.Error($"Request processed with {httpContext.Response.StatusCode}.");
                    }
                }
            }
            finally
            {
                responseBodyStream.Seek(0, SeekOrigin.Begin);
                await responseBodyStream.CopyToAsync(bodyStream);

                httpContext.Response.Body = bodyStream;

                responseBodyStream.Dispose();
            }
        }
Exemplo n.º 21
0
        public async Task Handle(IBotNotification <IClientEvent> notification)
        {
            var context = notification.Context;
            var @event  = notification.Event;

            _processed = _processed ??
                         context.Logger.CountOperation(ProcessedCounterName, resolution: ProcessedCounterResolution);
            var diagnosticProperties = new ILogEventEnricher[]
            {
                new PropertyEnricher("ConnectionId", context.Connection.Id),
                new PropertyEnricher("BotId", context.BotId),
                new PropertyEnricher("UserId", context.UserId),
                new PropertyEnricher("EventType", notification.Event.GetType().Name)
            };

            using (LogContext.Push(diagnosticProperties))
            {
                context.Logger.Debug("[Bot:{BotId}:{UserId}] Started to handle {EventType}.",
                                     context.BotId,
                                     context.UserId,
                                     @event.GetType().Name);
                try
                {
                    using (context.Logger.BeginTimedOperation(OperationDescription))
                    {
                        await _next.Handle(notification);
                    }
                }
                finally
                {
                    _processed.Increment();
                    context.Logger.Debug("[Bot:{BotId}:{UserId}] Finished to handle {EventType}.",
                                         context.BotId,
                                         context.UserId,
                                         @event.GetType().Name);
                }
            }
        }
Exemplo n.º 22
0
 public ILogger ForContext(ILogEventEnricher enricher)
 {
     throw new NotImplementedException();
 }
 internal static LoggerConfiguration With(LoggerEnrichmentConfiguration loggerEnrichmentConfiguration, ILogEventEnricher enricher)
 {
     return(loggerEnrichmentConfiguration.With(enricher));
 }
Exemplo n.º 24
0
 public ILogger ForContext(ILogEventEnricher enricher)
 {
     return(this);
 }
Exemplo n.º 25
0
 // .Enrich...
 // =======
 // expose `With(params ILogEventEnricher[] enrichers)` as if it was `With(ILogEventEnricher enricher)`
 static LoggerConfiguration With(
     LoggerEnrichmentConfiguration loggerEnrichmentConfiguration,
     ILogEventEnricher enricher)
 => loggerEnrichmentConfiguration.With(enricher);
Exemplo n.º 26
0
 // IAuditLogger Members
 public ILogger ForContext(ILogEventEnricher enricher)
 {
     return(_logger.ForContext(enricher));
 }
Exemplo n.º 27
0
 /// <inheritdoc />
 public ILogger ForContext(ILogEventEnricher enricher) => this;
Exemplo n.º 28
0
 public ILogger ForContext(ILogEventEnricher enricher)
 {
     return(new LoggerConfiguration().CreateLogger());
 }
 /// <summary>
 /// Create a logger that enriches log events via the provided enrichers.
 /// </summary>
 /// <param name="logger">The logger</param>
 /// <param name="enricher">Enricher that applies in the context.</param>
 /// <returns>A logger that will enrich log events as specified.</returns>
 public static ILog ForContext(this ILog logger, ILogEventEnricher enricher)
 {
     return((logger as SerilogLogger)?.ForContext(enricher));
 }
 internal ILog ForContext(ILogEventEnricher enricher)
 {
     return(new SerilogLogger(log.ForContext(enricher)));
 }