Is there a way to configure multiple Serilog RollingFiles through appSetting configuration

☆樱花仙子☆ 提交于 2019-12-12 11:44:01

问题


Is there a way to configure multiple Serilog RollingFiles through appSetting?

I want to create separate log files for Information and Error levels.


回答1:


Not directly - it's possible to use a setting prefix like:

.ReadFrom.AppSettings()
.ReadFrom.AppSettings(settingPrefix: "2")

And then add the additional sink like:

<add key="2:serilog:write-to:RollingFile.pathFormat" value="..." />

Baking this properly into the app settings configuration provider has been a "TODO" for a while.

If configuring the sinks in code is possible, that's probably the way to go.




回答2:


Configuring multiple logs is pretty simple in appsettings, mission is to use filter. i spent almost 3hours trying to figure out how to archieve this.

I ended up doing the following:

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"/>


来源:https://stackoverflow.com/questions/35315587/is-there-a-way-to-configure-multiple-serilog-rollingfiles-through-appsetting-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!