文章目录
- 1、所需的Nuget包
- 2、两种配置方式
- 2-1 代码形式(Program.cs)
- 2-2 配置文件形式(appsetting.json)
- 3、实现效果如下
1、所需的Nuget包
- 我项目的版本是.NET 8,其它版本安装适配版本即可
2、两种配置方式
2-1 代码形式(Program.cs)
-
在
Program.cs
文件中,添加如下代码//设置Serilog为日志管理 builder.Host.UseSerilog((context, loggerConfiguration) => { loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)//最小日志级别 .Enrich.FromLogContext() .WriteTo.Console()//输出到控制台 //按日志级别分别写入不同的日志文件中(可设置参数outputTemplate模板,有默认这里就不设置了) .WriteTo.Logger(configure => configure .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Information)//过滤 .WriteTo.File("Logs/Info/info.txt", rollingInterval: RollingInterval.Day)) .WriteTo.Logger(configure => configure .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Warning)//过滤 .WriteTo.File("Logs/Warn/warn.txt", rollingInterval: RollingInterval.Day)) .WriteTo.Logger(configure => configure .Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)//过滤 .WriteTo.File("Logs/Error/error.txt", rollingInterval: RollingInterval.Day)); });
2-2 配置文件形式(appsetting.json)
-
1、
appsetting.json
文件添加如下配置信息"Serilog": { "Using": [ "Serilog.Sinks.File" ], "MinimumLevel": { "Default": "Information",//默认日志输出级别 "Override": { "Microsoft": "Warning", "System": "Warning" } }, "WriteTo": [ { "Name": "Console" },//输出到控制台 {//info "Name": "Logger", "Args": { "configureLogger": { "Filter": [//过滤 { "Name": "ByIncludingOnly", "Args": { "expression": "@l = 'Information'" } } ], "WriteTo": [//写入 { "Name": "File", "Args": { "path": "Logs/Info/info.txt", "rollingInterval": "Day", "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {SourceContext}: {Message}{NewLine}{Exception}{NewLine}" } } ] } } }, {//warning "Name": "Logger", "Args": { "configureLogger": { "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "@l = 'Warning'" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/Warn/warn.txt", "rollingInterval": "Day", "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {SourceContext}: {Message}{NewLine}{Exception}{NewLine}" } } ] } } }, {//error "Name": "Logger", "Args": { "configureLogger": { "Filter": [ { "Name": "ByIncludingOnly", "Args": { "expression": "@l = 'Error'" } } ], "WriteTo": [ { "Name": "File", "Args": { "path": "Logs/Error/error.txt", "rollingInterval": "Day", "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {SourceContext}: {Message}{NewLine}{Exception}{NewLine}" } } ] } } } ], "Enrich": [ "FromLogContext", "WithThreadId" ] }
-
2、在
Program.cs
文件中添加如下代码进行Serilog
的注册使用//设置Serilog为日志管理 builder.Host.UseSerilog((context, loggerConfiguration) => { //读取配置文件中Serilog配置信息 loggerConfiguration.ReadFrom.Configuration(context.Configuration); });
3、实现效果如下
Logs/Info/info.txt
指定的日志文件路径是位于项目根路径下