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

标签 c# asp.net-core serilog

在我的 appsettings.json 中我写了:

{
    "Logging": {
        "PathLogsFile": "./Logs",
         "IncludeScopes": false,
         "LogLevel": {
             "Default": "Debug",
             "System": "Information",
             "Microsoft": "Information"
         }
    }
}

在构造函数中的 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();

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

最佳答案

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

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");

重要的是你不要像在 appSettings 中那样在你的键上加上 Serilog: 前缀。

关于c# - Serilog的ReadFrom.KeyValuePairs方法如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42875292/

相关文章:

c# - 为什么 CUDA 内核中的 z 总是零

.net - 单元测试 serilog 配置

asp.net - 如何使用身份验证通过 NLog 或 SeriLog 登录到 Elastic Search

c# - 连接字符串时使用char[]和StringBuilder和string没有区别

c# - 如何在 C# 中将对象类型传递给类型参数

c# - HttpClient PostAsync 不返回

c# - 无法识别 Serilog 的 AddSerilog

node.js - AggregateException : One or more errors occurred.(发生一个或多个错误。(无法启动 'npm'。要解决此问题:

c# - "VsTsc"任务无法用其输入 > 参数初始化

c# - 如何在 EF Core Code First 中自定义迁移生成?