如何使用 Serilog 的 ReadFrom.KeyValuePairs 方法?

Fab*_*Bit 2 c# serilog asp.net-core

在我的 appsettings.json 我写过:

{
    "Logging": {
        "PathLogsFile": "./Logs",
         "IncludeScopes": false,
         "LogLevel": {
             "Default": "Debug",
             "System": "Information",
             "Microsoft": "Information"
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

并在我的startup.cs文件中的构造函数中

var pathLogsFile = Configuration["Logging:PathLogsFile"];            
var logLevelApp = Configuration.GetSection("Logging:LogLevel:Default");

Log.Logger = new LoggerConfiguration()        
    .ReadFrom.KeyValuePairs(new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>(logLevelApp.Key, logLevelApp.Value)                        
        }.ToDictionary(x => x.Key, x => x.Value)) 
    .Enrich.FromLogContext()
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level == Serilog.Events.LogEventLevel.Error)
        .WriteTo.RollingFile(Path.Combine(pathLogsFile, "error-{Date}.log")))
    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(evt => evt.Level >= Serilog.Events.LogEventLevel.Debug)
        .WriteTo.RollingFile(Path.Combine(pathLogsFile, "log-{Date}.log")))
    .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

但是从 appsettings 读取的最低级别不起作用。有任何想法吗?我该如何解决?

asi*_*dis 6

我认为您不应该按照Parameswar Rao 的建议使用ReadFrom.KeyValuePairs和使用。但是,如果您真的想使用 KeyValuePair,这里有一些使用它的代码:ConfigurationBuilder .AddJsonFile("appsettings.json")

var logger = new LoggerConfiguration()
            .ReadFrom.KeyValuePairs(new Dictionary<string, string>() {
                { "write-to:File.fileSizeLimitBytes","20971520" },
                { "write-to:File.rollOnFileSizeLimit","true" },
                { "write-to:File.retainedFileCountLimit","10" },
                { "minimum-level","Debug" },
                { "write-to:File.path",@"C:\Temp\log.txt" },
                { "using:File","Serilog.Sinks.File" },
            }).CreateLogger();
        logger.Information("test");
Run Code Online (Sandbox Code Playgroud)

重要的部分是您不要Serilog:在 appSettings 中为您的键添加前缀。