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; } }
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>(); }
/// <inheritdoc /> public IApplicationLogger With(string propertyName, object value) { return(new ApplicationLogger( _config, _target.ForContext(propertyName, value), _loglevel)); }
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); }
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)); }
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); } }
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); }
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); }
/// <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; } } }
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); } }); }); }
public void LogDebug <T>(T details, string context, string message) { _serilogger.ForContext(context, details, true).Debug(message); }
/// <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))); }
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); }
public override ILogger Create(string name) { return(new SerilogLogger( logger.ForContext(Serilog.Core.Constants.SourceContextPropertyName, name), this)); }
/// <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); }
/// <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); }
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));