Serilog实战

发布时间 2023-09-19 13:40:22作者: 喜爱糖葫芦

提问

快速上手Serilog步骤

回答

  1. 引用
Serilog.Sinks.Async
Serilog.Sinks.File
Serilog.Sinks.Console

2.配置
appsetting.sjon 加入如下项

 "Serilog": {
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },

    "WriteTo:Async": {
      "Name": "Async",
      "Args": {
        "configure": [
          {
            "Name": "File",
            "Args": {
              "path": "logs/log-.txt",
              "rollingInterval": "Day",
              "outputTemplate": "{Timestamp:hh:mm:ss tt} [{Level:u3}] {Message}{NewLine}{Exception}"
            }
          },
          {
            "Name": "Console","Args": {
            "outputTemplate": "{Timestamp:hh:mm:ss tt} [{Level:u3}] {Message}{NewLine}{Exception}"
          }
          }
        ]
      }
    },
    "Enrich": [
      "FromLogContext",
      "WithMachineName",
      "WithThreadId"
    ]
  }
  1. 初始化
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var config = new ConfigurationBuilder()
   
    .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
    .Build();

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .ReadFrom.Configuration(config)
    .CreateLogger();
  1. 参考
    https://github.com/serilog/serilog-settings-configuration