Пример #1
0
        public void Log(LogEntry logEntry)
        {
            var user = accessFactory().CurrentUser();

            switch (logEntry.LogLevel)
            {
            case LogLevel.Information:
                log.ForContext("userId", user?.Id).Information(logEntry.Exception, logEntry.Message);
                break;

            case LogLevel.Debug:
                log.ForContext("userId", user?.Id).Debug(logEntry.Exception, logEntry.Message);
                break;

            case LogLevel.Warning:
                log.ForContext("userId", user?.Id).Warning(logEntry.Exception, logEntry.Message);
                break;

            case LogLevel.Error:
                log.ForContext("userId", user?.Id).Error(logEntry.Exception, logEntry.Message);
                break;

            case LogLevel.Fatal:
                log.ForContext("userId", user?.Id).Fatal(logEntry.Exception, logEntry.Message);
                break;

            default:
                break;
            }
        }
Пример #2
0
        public Gateway(StatelessServiceContext context, ILogger logger)
            : base(context)
        {
            PropertyEnricher[] properties = new PropertyEnricher[]
            {
                new PropertyEnricher("ServiceTypeName", context.ServiceTypeName),
                new PropertyEnricher("ServiceName", context.ServiceName),
                new PropertyEnricher("PartitionId", context.PartitionId),
                new PropertyEnricher("InstanceId", context.ReplicaOrInstanceId),
            };

            logger.ForContext(properties);

            Logger = new LoggerFactory().AddSerilog(logger.ForContext(properties)).CreateLogger <Gateway>();
        }
Пример #3
0
 /// <inheritdoc />
 public IApplicationLogger With(string propertyName, object value)
 {
     return(new ApplicationLogger(
                _config,
                _target.ForContext(propertyName, value),
                _loglevel));
 }
Пример #4
0
        IDocumentStore ConfigureRaven()
        {
            var store = new DocumentStore
            {
                Urls     = new[] { Configuration["RavenDb:Url"] },
                Database = Configuration["RavenDb:Database"]
            };

            if (Environment.IsDevelopment())
            {
                store.OnBeforeQuery += (_, args)
                                       => args.QueryCustomization
                                       .WaitForNonStaleResults()
                                       .AfterQueryExecuted(result =>
                {
                    Log.ForContext("SourceContext", "Raven").Debug("{index} took {duration}", result.IndexName, result.DurationInMs);
                });
            }

            try
            {
                store.Initialize();
                Log.Information("Connection to {url} document store established.", store.Urls[0]);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to establish connection to \"{store.Urls[0]}\" document store!" +
                          $"Please check if https is properly configured in order to use the certificate.", ex);
            }

            try
            {
                var record = store.Maintenance.Server.Send(new GetDatabaseRecordOperation(store.Database));
                if (record == null)
                {
                    store.Maintenance.Server
                    .Send(new CreateDatabaseOperation(new DatabaseRecord(store.Database)));

                    Log.Debug("{database} document store database created.", store.Database);
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(
                          $"Failed to ensure that \"{store.Database}\" document store database exists!", ex);
            }

            try
            {
                IndexCreation.CreateIndexes(Assembly.GetExecutingAssembly(), store);
                Log.Information("{database} document store database indexes created or updated.", store.Database);
            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Failed to create or update \"{store.Database}\" document store database indexes!", ex);
            }

            return(store);
        }
Пример #5
0
 public static Serilog.ILogger Here(
     this Serilog.ILogger logger,
     [CallerMemberName] string memberName = "",
     [CallerFilePath] string filePath     = "",
     [CallerLineNumber] int lineNumber    = 0)
 {
     return(logger.ForContext("MemberName", "in method " + memberName)
            .ForContext("FilePath", "at " + filePath)
            .ForContext("FileName", Path.GetFileNameWithoutExtension(filePath))
            .ForContext("LineNumber", ":" + lineNumber));
 }
Пример #6
0
        private static void ConfigureLogger()
        {
            _logger = new LoggerConfiguration()
                      .Enrich.FromLogContext()
                      .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] [{Module}] [{Context}] {Message:lj}{NewLine}{Exception}")
                      .WriteTo.RollingFile(new CompactJsonFormatter(), "logs/logs")
                      .CreateLogger();

            _loggerForApi = _logger.ForContext("Module", "API");

            _loggerForApi.Information("Logger configured");
        }
        /// <summary>
        /// Configures logging
        /// </summary>
        /// <param name="loggerFactory"></param>
        public void Configure(IConfiguration configuration)
        {
            logger = new LoggerConfiguration()
                     .ReadFrom.Configuration(configuration)
                     .WriteTo.EventFlow(diagnosticPipeline)
                     .CreateLogger();

            if (logEnrichments.Count > 0)
            {
                logger = logger.ForContext(logEnrichments);
            }
        }
Пример #8
0
        public static void Initialize(
            string connectionString,
            IExecutionContextAccessor executionContextAccessor,
            ILogger logger)
        {
            var moduleLogger = logger.ForContext("Module", "Payments");

            ConfigureCompositionRoot(connectionString, executionContextAccessor, moduleLogger);

            QuartzStartup.Initialize(moduleLogger);

            EventsBusStartup.Initialize(moduleLogger);
        }
Пример #9
0
        static ILogger LogForErrorContext(HttpContext httpContext)
        {
            var request = httpContext.Request;

            var loggedHeaders = request.Headers
                                .Where(h => HeaderWhitelist.Contains(h.Key))
                                .ToDictionary(h => h.Key, h => h.Value.ToString());

            var result = Log
                         .ForContext("RequestHeaders", loggedHeaders, destructureObjects: true)
                         .ForContext("RequestHost", request.Host)
                         .ForContext("RequestProtocol", request.Protocol);

            return(result);
        }
Пример #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SerilogLoggerProvider"/> class.
        /// </summary>
        /// <param name="logger">A Serilog logger to pipe events through; if null, the static <see cref="Log"/> class will be used.</param>
        /// <param name="dispose">If true, the provided logger or static log class will be disposed/closed when the provider is disposed.</param>
        public SerilogLoggerProvider(ILogger logger = null, bool dispose = false)
        {
            if (logger != null)
            {
                _logger = logger.ForContext(new[] { this });
            }

            if (dispose)
            {
                if (logger != null)
                {
                    _dispose = () => (logger as IDisposable)?.Dispose();
                }
                else
                {
                    _dispose = Log.CloseAndFlush;
                }
            }
        }
Пример #11
0
    private void Start()
    {
        _infoButton.onClick.AddListener(() =>
        {
            using (UnityContext.PushObject(this))
            {
                _logger.Information("This is an info");
            }
        });

        var testLogger = _logger.ForContext(Constant.CATEGORY_NAME, "Test");

        _warningButton.onClick.AddListener(() => testLogger.Warning("This is a warning"));
        _errorButton.onClick.AddListener(() =>
        {
            try
            {
                throw new InvalidOperationException("Invalid stuff");
            }
            catch (Exception e)
            {
                _logger.Error(e, "This is an error");
            }
        });
        _threadButton.onClick.AddListener(() =>
        {
            var stopWatch = Stopwatch.StartNew();

            ThreadPool.QueueUserWorkItem(state =>
            {
                stopWatch.Stop();
                using (UnityContext.PushObject(this))
                {
                    _logger.Information("Log from thread {Id}, Invoke took: {Elapsed}",
                                        Thread.CurrentThread.ManagedThreadId, stopWatch.Elapsed);
                }
            });
        });
    }
Пример #12
0
 public void LogDebug <T>(T details, string context, string message)
 {
     _serilogger.ForContext(context, details, true).Debug(message);
 }
Пример #13
0
 /// <summary>
 /// Create a logger with the name <paramref name="name"/>.
 /// </summary>
 /// <param name="name">Name of the logger to be created.</param>
 /// <returns>New Logger</returns>
 public ILogger CreateLogger(string name)
 {
     return(new Logger(_logger.ForContext(Constants.SourceContextPropertyName, name)));
 }
Пример #14
0
 public static ILogger GetLogger(Type declaringType) => new SerilogLogger(serilogLogger.ForContext(declaringType));
    /// <summary>
    ///     Create and configure the logger.
    /// </summary>
    /// <remarks>
    ///     Additional Serilog services are registered during <see cref="HostBuilderExtensions.ConfigureUmbracoDefaults" />.
    /// </remarks>
    public static IServiceCollection AddLogger(
        this IServiceCollection services,
        IHostEnvironment hostEnvironment,
        IConfiguration configuration)
    {
        // TODO: WEBSITE_RUN_FROM_PACKAGE - can't assume this DIR is writable - we have an IConfiguration instance so a later refactor should be easy enough.
        var loggingDir = hostEnvironment.MapPathContentRoot(Constants.SystemDirectories.LogFiles);
        ILoggingConfiguration loggingConfig = new LoggingConfiguration(loggingDir);

        var umbracoFileConfiguration = new UmbracoFileConfiguration(configuration);

        services.TryAddSingleton(umbracoFileConfiguration);
        services.TryAddSingleton(loggingConfig);
        services.TryAddSingleton <ILogEventEnricher, ApplicationIdEnricher>();

        ///////////////////////////////////////////////
        // Bootstrap logger setup
        ///////////////////////////////////////////////

        LoggerConfiguration serilogConfig = new LoggerConfiguration()
                                            .MinimalConfiguration(hostEnvironment, loggingConfig, umbracoFileConfiguration)
                                            .ReadFrom.Configuration(configuration);

        Log.Logger = serilogConfig.CreateBootstrapLogger();

        ///////////////////////////////////////////////
        // Runtime logger setup
        ///////////////////////////////////////////////

        services.AddSingleton(sp =>
        {
            var logger = new RegisteredReloadableLogger(Log.Logger as ReloadableLogger);

            logger.Reload(cfg =>
            {
                cfg.MinimalConfiguration(hostEnvironment, loggingConfig, umbracoFileConfiguration)
                .ReadFrom.Configuration(configuration)
                .ReadFrom.Services(sp);

                return(cfg);
            });

            return(logger);
        });

        services.AddSingleton <ILogger>(sp =>
        {
            ILogger logger = sp.GetRequiredService <RegisteredReloadableLogger>().Logger;
            return(logger.ForContext(new NoopEnricher()));
        });

        services.AddSingleton <ILoggerFactory>(sp =>
        {
            ILogger logger = sp.GetRequiredService <RegisteredReloadableLogger>().Logger;
            return(new SerilogLoggerFactory(logger));
        });

        // Registered to provide two services...
        var diagnosticContext = new DiagnosticContext(Log.Logger);

        // Consumed by e.g. middleware
        services.TryAddSingleton(diagnosticContext);

        // Consumed by user code
        services.TryAddSingleton <IDiagnosticContext>(diagnosticContext);

        return(services);
    }
Пример #16
0
 public override ILogger Create(string name)
 {
     return(new SerilogLogger(
                logger.ForContext(Serilog.Core.Constants.SourceContextPropertyName, name),
                this));
 }
Пример #17
0
        /// <summary>
        /// Write a log event with the <see cref="!:LogEventLevel.Debug" /> level and associated exception.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="exception">Exception related to the event.</param>
        /// <param name="messageTemplate">Message template describing the event.</param>
        /// <param name="propertyValues">Objects positionally formatted into the message template.</param>
        /// <example>
        /// Log.Debug(ex, "Swallowing a mundane exception.");
        /// </example>
        public void Debug(Type context = null, Exception exception = null, string messageTemplate = null, params object[] propertyValues)
        {
            var logger = (context != null) ? _log.ForContext(context) : _log;

            logger.Debug(exception, messageTemplate, propertyValues);
        }
Пример #18
0
 /// <summary>
 /// Writes an debug message to the log
 /// </summary>
 /// <param name="message">The message to log</param>
 public void Debug(string message)
 {
     _logger.ForContext(_type).Debug(message);
 }
Пример #19
0
 public ILogger CreateLogger(string name)
 {
     return(new SerilogLoggerAdapter(_logger.ForContext("SourceContext", name)));
 }
 /// <summary>
 /// Temporary enrichment of a new property
 /// </summary>
 /// <param name="propertyName"></param>
 /// <param name="propertyValue"></param>
 /// <param name="destructureObjects"></param>
 /// <returns></returns>
 public Organica.Common.Logger.ILogger ForContext(string propertyName, object propertyValue, bool destructureObjects = false) =>
 new Logger(_logger.ForContext(propertyName, propertyValue, destructureObjects));