Search code examples
c#asp.net-coreserilogserilog-aspnetcoreserilog-filter

Serilog categorized multiple Sinks


I want to separate my logs in three different parts. Searched for logging libraries and the best one I found is Serilog.

  1. write http request logs to daily rolling txt files.
  2. write logs containing exceptions to Seq.
  3. write all logs except http request logs to a local SQLite database (for users access).

Used the following code but nothing works:

new LoggerConfiguration().Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
.WithDefaultDestructurers()
.WithRootName("Message").WithRootName("Exception").WithRootName("Exception"))
.Enrich.WithProperty("App.Version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0.0")
.Enrich.WithMachineName()
.Enrich.WithEnvironmentUserName()
            .WriteTo.SQLite(GetFilePath("logs.db"))
            .Filter.ByIncludingOnly(Matching.FromSource("Serilog.AspNetCore.RequestLoggingMiddleware"))
            .WriteTo.File(
                GetFilePath("access.log"),
                rollingInterval: RollingInterval.Day,
                retainedFileCountLimit: 31
            )
            .Filter.ByIncludingOnly(LogEvent => LogEvent.Exception != null)
            .WriteTo.Seq("https://mylogger.appserver.com/")

Removed second filter (request logs) and now it just writes exception logs in both Seq and local SQLite db.


Solution

  • You could use "sub logger" to configure different filter for each sink like following:

    Log.Logger = new LoggerConfiguration()
                    .Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
                    .WithDefaultDestructurers()
                    .WithRootName("Message").WithRootName("Exception").WithRootName("Exception"))
                    .Enrich.WithProperty("App.Version", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0.0")
                    .Enrich.WithMachineName()
                    .Enrich.WithEnvironmentUserName()
                    .WriteTo.Logger(l => l
                        .Filter.ByExcluding(Matching.FromSource("Serilog.AspNetCore.RequestLoggingMiddleware"))
                        .WriteTo.SQLite(GetFilePath("logs.db")))
                    .WriteTo.Logger(l => l
                        .Filter.ByIncludingOnly(Matching.FromSource("Serilog.AspNetCore.RequestLoggingMiddleware"))
                        .WriteTo.File(GetFilePath("access.log"),rollingInterval: RollingInterval.Day,retainedFileCountLimit: 31))
                    .WriteTo.Logger(l => l
                        .Filter.ByIncludingOnly(LogEvent => LogEvent.Exception != null)
                        .WriteTo.Seq("https://mylogger.appserver.com/"))
                    .CreateLogger();
    

    (Use Filter.ByExcluding to exclude a source)