有没有办法通过配置文件配置Serilog子记录器?
问题描述:
目前我有用代码编写的所有配置。我使用子记录器进行筛选并更改记录的存储。有没有办法从配置文件中做到这一点。因为我想为解决方案中的每个上下文都有单独的配置文件。有没有办法通过配置文件配置Serilog子记录器?
答
如果子记录器的数量是固定在编译的时候,你可以使用配置前缀来做到这一点:
Log.Logger = new LoggerConfiguration()
.ReadFrom.AppSettings() // default file
.WriteTo.Logger(lc => lc
.ReadFrom.AppSettings(filePath: "other1.config"))
.WriteTo.Logger(lc => lc
.ReadFrom.AppSettings(filePath: "other2.config"))
.CreateLogger();
有在Serilog.Settings.AppSettings不支持,但在理论上没有什么预防如果某人能够实施它,它会被添加。
答
试试这个
Startup.cs/Global.asax.cs中
Log.Logger = new LoggerConfiguration()
.WriteTo
.Logger(x => x.Filter
.ByIncludingOnly(logEvent => logEvent.Level == Serilog.Events.LogEventLevel.Error)
.ReadFrom
.AppSettings("error"))
.WriteTo
.Logger(x => x.Filter
.ByIncludingOnly(logEvent => logEvent.Level == Serilog.Events.LogEventLevel.Information)
.ReadFrom
.AppSettings("info")).CreateLogger()
的Web.Config
<add key ="error:serilog:using:RollingFile" value="Serilog.Sinks.RollingFile"/>
<add key ="error:serilog:write-to:RollingFile.pathFormat" value="C:\log\error {Date}.txt"/>
<add key ="error:serilog:write-to:RollingFile.formatter" value="Serilog.Formatting.Json.JsonFormatter"/>
<add key ="info:serilog:using:RollingFile" value="Serilog.Sinks.RollingFile"/>
<add key ="info:serilog:write-to:RollingFile.pathFormat" value="C:\log\info {Date}.txt"/>
<add key ="info:serilog:write-to:RollingFile.formatter" value="Serilog.Formatting.Json.JsonFormatter"/>
+0
请不要添加[相同的答案](http://stackoverflow.com/a/41989190/4687348)亩一些问题。回答最好的一个,并将其余标记为重复。请参阅[是否可以为几个问题添加重复答案?](http://meta.stackexchange.com/q/104227/347985) – FelixSFD
这可能是有用的,[提问]:HTTP: //stackoverflow.com/a/41989190/7038900 – Spharah