Asp.Net Core 8.0 使用 Serilog 按日志级别写入日志文件的两种方式
1、所需的Nuget包
本文项目的版本是.NET 8.0,如果使用其它版本安装适配版本即可。
Serilog.AspNetCore(8.0.2)
Serilog.Sinks.File(5.0.0)
Serilog.Expressions(5.0.0)
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)
2.2.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.2.2、在Program.cs文件中添加如下代码进行Serilog的注册使用
//设置Serilog为日志管理
builder.Host.UseSerilog((context, loggerConfiguration) =>
{
//读取配置文件中Serilog配置信息
loggerConfiguration.ReadFrom.Configuration(context.Configuration);
});
3、实现效果如下
Logs/Info/info.txt 指定的日志文件路径是位于项目根路径下
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。
原文地址:https://blog.csdn.net/hefeng_aspnet/article/details/144826084
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!