Serilog - 单独的信息文件,使用 appsetting.json 例外 [英] Serilog - Separate files for Information, exception using appsetting.json
问题描述
我正在使用滚动将所有日志写入一个文件.但我想通过 Information
、Warning
和 Exceptions
滚动文件将它们分开.
I am writing all logs into one file(s) using rolling. But I want to separate them by Information
, Warning
and Exceptions
rolling files.
我现在的配置是这样的
"Serilog": {
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
"pathFormat": "logs\log-{Hour}.log",
"rollOnFileSizeLimit ": true,
"retainedFileCountLimit ": null,
"rollingInterval": "Hour",
"fileSizeLimitBytes": 5000000
}
}
]
},
班级
public ILogger GetLogger()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
_logger =
new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
return _logger ;
}
推荐答案
在 Serilog 中,您可以通过 子记录器 或通过 Serilog.Sinks.Map.
In Serilog you could do this separation either via sub-loggers or via Serilog.Sinks.Map.
您无法通过 appsetting.json
配置整个管道,但您可以使用自定义键轻松配置 appsetting.json
中每个文件的路径选择,并在通过代码配置日志管道时使用它.
You wouldn't be able to configure the whole pipeline via appsetting.json
but you can easily configure the path of each file in appsetting.json
using a custom key of your choice, and use that when configuring the log pipeline via code.
使用带有过滤器的子记录器的示例应用于每个人:
Example using sub-loggers with a filter applied to each of them:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Logger(c =>
c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Debug)
.WriteTo.File("Debug.log"))
.WriteTo.Logger(c =>
c.Filter.ByIncludingOnly(e => e.Level == LogEventLevel.Error)
.WriteTo.File("Error.log"))
.CreateLogger();
Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");
Log.CloseAndFlush();
<小时>
使用 Serilog.Sinks.Map 映射每个 LogEventLevel 的示例代码> 到不同的文件.
Example using Serilog.Sinks.Map mapping each LogEventLevel
to a different file.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Map(evt => evt.Level, (level, wt) => wt.File($"{level}.log"))
.CreateLogger();
Log.Debug("This goes to Debug.log only");
Log.Error("This goes to Error.log only");
Log.CloseAndFlush();
这篇关于Serilog - 单独的信息文件,使用 appsetting.json 例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!