我想把微软的日志和自己应用的日志分别写入到不同的文件中去
参考 Serilog : Log to different files 中的回答:
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();
我想在appsettings.json进行配置,不知道这个过滤条件能不能配置进去?
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.txt",
"rollingInterval": "Day"
}
},
{
"Name": "Console",
"Args": {}
}
]
},
@火焰人生: 参考 Serilog : how do you specify a filter expression in config file 中的回答:
Install-Package Serilog.Filters.Expressions
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "SourceContext = 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
}
}
]
@dudu: 下面这样配置,不起作用
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"Serilog": {
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "system-.txt",
"rollingInterval": "Day"
},
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "SourceContext == 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
}
}
]
},
{
"Name": "File",
"Args": {
"path": "web-.txt",
"rollingInterval": "Day"
},
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"expression": "SourceContext == 'Microsoft.AspNetCore.Hosting.Internal.WebHost'"
}
}
]
},
{
"Name": "Console",
"Args": {}
}
]
},
"AllowedHosts": "*"
}
@火焰人生: 在 "Serilog"
下添加 "Using": [ "Serilog.Sinks.File" ]
试试
@dudu: 还是没起作用
可以试一下 按月拆文件夹,按日和级别拆文件
appsetting.json 可能不太好配,用是没问题的
pathPrefixKey变量为目录前缀,比如 d:/logs/xxx_api
输出
D:\logs\xxx_api\2020-03\debug-20200331.txt
D:\logs\xxx_api\2020-03\warning-20200331.txt
D:\logs\xxx_api\2020-03\information-20200331.txt
D:\logs\xxx_api\2020-04\debug-20200428.txt
D:\logs\xxx_api\2020-04\warning-20200428.txt
D:\logs\xxx_api\2020-04\information-20200428.txt
便于按月按日分析问题,也可以修改保存规则,代码如下:
.WriteTo.Map(
le => new Tuple<DateTime, LogEventLevel>(
new DateTime(le.Timestamp.Year, le.Timestamp.Month, le.Timestamp.Day), le.Level),
(key, log) => log.Async(a =>
a.File(new CompactJsonFormatter(),
Path.Combine(pathPrefixKey, $"{key.Item1:yyyy-MM}/{key.Item2.ToString().ToLower()}-.txt"),
rollingInterval: RollingInterval.Day, retainedFileCountLimit: null)),
sinkMapCountLimit: 1);
能说一下这个都是引得哪个包吗?