有没有办法通过配置文件配置 Serilog 子记录器?

Is there a way to configure Serilog sub loggers via configuration file?

目前我已经用代码编写了所有配置。我使用 subloggers 来过滤和更改日志记录的存储。有什么办法可以从配置文件中做到这一点。因为我想为解决方案中的每个上下文创建一个单独的配置文件。

如果子记录器的数量在构建时是固定的,你可以使用配置前缀来做到这一点:

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