Serilog : Log to different files

后端 未结 3 2283
广开言路
广开言路 2021-02-18 17:38

I am logging events of all types to single Json file irrespective of LogLevel. Now I have a requirement to log some custom performance counters to a seperate Json file. How can

相关标签:
3条回答
  • 2021-02-18 18:00

    You can do this by first making sure the performance counter events are tagged with either a particular property value (OpenMappedContext() in LibLog) or from a particular type/namespace.

    var log = LogProvider.For<MyApp.Performance.SomeCounter>()
    log.Info(...);
    

    When configuring Serilog, a sub-logger with filter applied can send just the required events to the second file.

    Log.Logger = new LoggerConfiguration()
        .WriteTo.Logger(lc => lc
            .Filter.ByExcluding(Matching.FromSource("MyApp.Performance"))
            .WriteTo.File("first.json", new JsonFormatter()))
        .WriteTo.Logger(lc => lc
            .Filter.ByIncludingOnly(Matching.FromSource("MyApp.Performance"))
            .WriteTo.File("second.json", new JsonFormatter()))
        .CreateLogger();
    
    0 讨论(0)
  • 2021-02-18 18:01

    If you want to have an independent logging pipeline, just make another instance. This is robbed and adapted from https://github.com/serilog/serilog/wiki/Lifecycle-of-Loggers:

    using (var performanceCounters = new LoggerConfiguration()
            .WriteTo.File(@"myapp\log.txt")
            .CreateLogger())
    {
        performanceCounters.Information("Performance is really good today ;-)");
    
        // Your app runs, then disposal of `performanceCounters` flushes any buffers
    }
    
    0 讨论(0)
  • 2021-02-18 18:13

    We can set it up in the configuration files too. Given below is a sample in the appsettings.json to split the log the rolling files based on levels

    {
     
      "Serilog": {
        "MinimumLevel": {
          "Default": "Debug",
          "Override": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
          }
        },
        "WriteTo": [
          {
            "Name": "Logger",
            "Args": {
              "configureLogger": {
                "Filter": [
                  {
                    "Name": "ByIncludingOnly",
                    "Args": {
                      "expression": "(@Level = 'Error' or @Level = 'Fatal' or @Level = 'Warning')"
                    }
                  }
                ],
                "WriteTo": [
                  {
                    "Name": "File",
                    "Args": {
                      "path": "Logs/ex_.log",
                      "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                      "rollingInterval": "Day",
                      "retainedFileCountLimit": 7
                    }
                  }
                ]
              }
            }
          },
          {
            "Name": "Logger",
            "Args": {
              "configureLogger": {
                "Filter": [
                  {
                    "Name": "ByIncludingOnly",
                    "Args": {
                      "expression": "(@Level = 'Information' or @Level = 'Debug')"
                    }
                  }
                ],
                "WriteTo": [
                  {
                    "Name": "File",
                    "Args": {
                      "path": "Logs/cp_.log",
                      "outputTemplate": "{Timestamp:o} [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                      "rollingInterval": "Day",
                      "retainedFileCountLimit": 7
                    }
                  }
                ]
              }
            }
          }
        ],
        "Enrich": [
          "FromLogContext",
          "WithMachineName"
        ],
        "Properties": {
          "Application": "MultipleLogFilesSample"
        }
      }
    }
    

    Then, you will only need to modify the CreateHostBuilder method in Program.cs file to read it from the configuration file

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog((hostingContext, loggerConfig) =>
                    loggerConfig.ReadFrom.Configuration(hostingContext.Configuration)
                );
    

    For more details, refer the post here

    0 讨论(0)
提交回复
热议问题