我正在使用滚动将所有日志写入一个文件。但是我想通过Information
,Warning
和Exceptions
滚动文件将它们分开。
我当前的配置是这样
"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
}
}
]
},
class
public ILogger GetLogger()
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
_logger =
new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
return _logger ;
}
我尚未测试,但通过推断文档:您可以尝试在appconf文件中创建2个部分
"ErrorLog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
"pathFormat": "logs\\ Errorlog-{Hour}.log",
"rollingInterval": "Hour",
"restrictedToMinimumLevel": "Error"
}
}
]
},
"InfoLog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "RollingFile",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}",
"pathFormat": "logs\\ Infolog-{Hour}.log",
"rollingInterval": "Hour",
"restrictedToMinimumLevel": "Information"
}
}
]
}
您创建了2个记录器:
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var errorSection = configuration.GetSection("ErrorLog");
var infoSection = configuration.GetSection("InfoLog");
_errorlog = new LoggerConfiguration()
.ReadFrom
.ConfigurationSection(errorSection)
.CreateLogger();
_infolog = new LoggerConfiguration()
.ReadFrom
.ConfigurationSection(infoSection)
.CreateLogger();
在Serilog中,您可以通过sub-loggers或通过Serilog.Sinks.Map进行此分离。
您将无法通过appsetting.json
配置整个管道,但是您可以使用所选的自定义键轻松配置appsetting.json
中每个文件的路径,并在通过代码配置日志管道时使用该路径。
使用sub-loggers并对其应用过滤器的示例:
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
映射到另一个文件的示例。
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();