Skip to content

Serilog日志组件

约 982 字大约 3 分钟

组件

2024-03-16

github:项目集成 - 源代码文档

在.NET6 WPF中使用

//需要先引入Serilog、Serilog.Extensions.Hosting包
 new HostBuilder()
      //.ConfigureServices((context, services) =>{services.AddLogging(loggerbuild => loggerbuild.AddSerilog(dispose: true));}) // 这句
      .UseSerilog() // 或者这句都能引入 (需要Serilog.Extensions.Hosting)
      //.UseSerilog((hostingContext, services, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)) //直接内联初始化 就不用在OnStartup()中单独new LoggerConfiguration().CreateLogger()了
      .Build();

在程序中配置

 
 private async void OnStartup(object sender, StartupEventArgs e)
        {
            Log.Logger = new LoggerConfiguration()
                 .Enrich.WithProperty("zidingyi", "1.0.0.0") //增加新的属性,可用于展示到输出模板
                 .Enrich.WithProperty("Count", 2)

                  //.Destructure.ByTransforming<HttpRequest>(r => new { RawUrl = r.RawUrl, Method = r.Method }) //格式化http请求输出 未测试


                  .MinimumLevel.Verbose() //设置日志写入的最低等级,其他方式中自己设置的等级只能高于这个等级,低于就不生效。 Serilog 默认输出等级是info    
                  .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning) //重写系统日志等级 让其不输出到info
                  .MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning)
                    
                    //写入文件引入 Serilog.Sinks.File 
                  .WriteTo.File("log-info.log",
                  rollOnFileSizeLimit:true,  //开启根据大小分文件
                  fileSizeLimitBytes: 1024, //10*1024*1024=10MB 单文件最大体积 达到后生成新的文件
                  retainedFileCountLimit:60,// 保留文件数量,  默认31,传空一直保留
                  rollingInterval: RollingInterval.Day,
                  outputTemplate: "{Timestamp:yy/MM/dd HH:mm:ss.fff} [{Level:w4}] {Message:lj}{NewLine}{Exception}{NewLine}"
                 /*
                  * {Level:u3} {Level:w4}:输出日志等级u代表大写 w代表小写  数字代表输出几位 3:inf INF ERR err  4:INFO ERRO
                  * {Message:lj} :j:输出内容按照json格式,字符串 还是输出字符串
                  * {Properties:j} 输出上下文信息
                  * 
                  */
                 )

                 .WriteTo.File("log-err.log",
                 rollingInterval: RollingInterval.Day,
                 restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error, //单独记录错误等级的日志
                 outputTemplate: "{zidingyi} {Timestamp:yy/MM/dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}")

                 //写入数据接口引入对应的数据库包 Serilog.Sinks.SQLite
                 .WriteTo.SQLite(@"Log\log.db", "log")


                 //.WriteTo.Console(restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose)
                 .CreateLogger();
            await _host.StartAsync();
        }

在配置文件中使用

        private async void OnStartup(object sender, StartupEventArgs e)
        {
            //使用配置文件 引入Serilog.Settings.Configuration包
            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration).CreateLogger();


            await _host.StartAsync();
        }

Github:serilog-settings-configuration 详解

{
  "Serilog": {
    "MinimumLevel": {
      "default": "Debug",
      "Override": {     //重写系统日志等级,提高系统日志等级 不输出
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "loginfo-.log", //自动添加日期 loginfo-20230628.log
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Information",
          "rollOnFileSizeLimit": true, //开启根据大小分文件, 不开启开关,文件大小达到后会停止写入
          "fileSizeLimitBytes": 10485760, //10*1024*1024=10485760
          "retainedFileCountLimit": 3, //保留的文件个数
          "outputTemplate": "{Timestamp:yy/MM/dd HH:mm:ss.fff} [{Level:w4}] {Message:lj}{NewLine}{Exception}{NewLine}"
        }
      },
      {
        "Name": "File",
        "Args": {
          "path": "logerr-.log",
          "rollingInterval": "Day",
          "restrictedToMinimumLevel": "Error"
        }
      },
      {
        "Name": "SQLite",
        "Args": {
          "sqliteDbPath": "Log\\mylog.db"
        }
      }
    ]
  }
}

File Sink本身并不直接支持Filter配置。 Filter是Logger级别的概念,不是Sink级别的:它是Logger pipeline的一部分,而不是单个Sink的特性。 过滤依赖Serilog.Expressions

主 Sink配置过滤

主Logger只会输出Scan日志,其他日志都被过滤掉了。

{
    "Serilog": {
        "Using": ["Serilog.Sinks.Debug", "Serilog.Sinks.File","Serilog.Expressions"],
        "MinimumLevel": {
            "default": "Debug",
            "Override": {
                "Microsoft": "Warning",
                "System": "Warning"
            }
        },
        "Filter": [
            {
                "Name": "ByIncludingOnly",
                "Args": {
                    "expression": "LogType = 'Scan'"
                }
            }
        ],
        "WriteTo": [
            {
                "Name": "File",
                "Args": {
                    "path": "Log/{0:Date}/Scan-.txt",
                    "rollingInterval": "Day",
                    "outputTemplate": "{Timestamp:HH:mm:ss.fff} [{Level:w4}] {Message:lj}{NewLine}{Exception}{NewLine}",
                    "fileSizeLimitBytes": 10485760,
                    "retainedFileCountLimit": 30
                }
            }
        ]
    }
}

子Logger配置配置过滤

{
    "Serilog": {
        "Using": ["Serilog.Sinks.Debug", "Serilog.Sinks.File","Serilog.Expressions"], //, "Serilog.Sinks.SQLite",  "Serilog.Formatting.Compact"
        "MinimumLevel": {
            "default": "Debug", //Verbose Debug Information Warning Error Fatal
            "Override": {
                //重写系统日志等级,提高系统日志等级 不输出
                "Microsoft": "Warning",
                "System": "Warning"
            }
        },
      "WriteTo": [
        { "Name": "Debug" },
        //{
        //  "Name": "File",
        //  "Args": {
        //    "path": "Log/{0:Date}/All.log",
        //    "restrictedToMinimumLevel": "Debug",
        //    //"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact", //json格式不能自定义输出outputTemplate
        //    "rollOnFileSizeLimit": true, //开启根据大小分文件, 不开启开关,文件大小达到后会停止写入
        //    "fileSizeLimitBytes": 10485760, //10*1024*1024=10485760
        //    "retainedFileCountLimit": 30, //保留的文件个数 保留一个月的日志
        //    "outputTemplate": "{Timestamp:HH:mm:ss.fff} [{Level:w4}] {Message:lj}{NewLine}{Exception}{NewLine}"
        //  }
        //},
        //{
        //  "Name": "File",
        //  "Args": {
        //    "path": "Log/{0:Date}/Error.log",
        //    "restrictedToMinimumLevel": "Error",
        //    "rollOnFileSizeLimit": true,
        //    "fileSizeLimitBytes": 10485760,
        //    "retainedFileCountLimit": 30,
        //    "outputTemplate": "{Timestamp:HH:mm:ss.fff} [{Level:w4}] {Message:lj}{NewLine}{Exception}{NewLine}"
        //  }
        //},
        {
          "Name": "Logger",
          "Args": {
            "configureLogger": {
              "Filter": [
                {
                  "Name": "ByIncludingOnly",
                  "Args": { "expression": "LogType = 'Scan'" } 
                }
              ],
              "WriteTo": [
                {
                  "Name": "File",
                  "Args": {
                    "path": "Log/{0:Date}/Scan.log",
                    "restrictedToMinimumLevel": "Information",
                    "outputTemplate": "{Timestamp:HH:mm:ss.fff} {Message:lj}{NewLine}{Exception}"
                  }
                }
              ]
            }
          }
        },
      ]
    }
}

4 https://github.com/serilog/serilog/wiki/Provided-Sinks