Serilog ReadFrom配置

时间:2018-08-31 13:04:56

标签: logging asp.net-core .net-core serilog

我正在尝试使用Serilog.Settings.Configuration预发布的NuGet包从appsettings.json加载我的Serilog配置。但是,当我使用Configuration.GetSection加载它时,该值继续返回为null。

这是我的Program.cs文件中的内容:

return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(
    (hostingContext, loggingBuilder) =>
    {
        loggingBuilder.ClearProviders();
        loggingBuilder.AddSerilog(
            new LoggerConfiguration()
                .ReadFrom.ConfigurationSection(hostingContext.Configuration.GetSection("Serilog"))
                .CreateLogger()
        );
    }
);

这是我的appsettings.json文件中的内容:

{
"Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
        "Default": "Verbose",
        "Override": {
            "Microsoft": "Verbose",
            "System": "Verbose",
            "Microsoft.AspNetCore.Authentication": "Verbose"
        }
    },
    "WriteTo": [
        {
            "Name": "MSSqlServer",
            "Args": {
                "connectionString": "*my_connectionString*",
                "tableName": "ErrorLog"
            }
        }
    ]
}}

已安装NuGet软件包:

  • Microsoft.AspNetCore.App v2.1.1
  • Serilog v2.7.1
  • Serilog.AspNetCore v2.1.1
  • Serilog.Extensions.Logging v2.0.2
  • Serilog.Settings.Configuration v3.0.0-dev-00119
  • Serilog.Sinks.MSSqlServer v5.1.2

3 个答案:

答案 0 :(得分:2)

我这样配置它:

return WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                .ReadFrom.Configuration(hostingContext.Configuration))
            .Build();

默认情况下,Serilog在配置中查找Serilog部分

答案 1 :(得分:0)

我这样配置

     public static void Main(string[] args)
     {
        var _config = new ConfigurationBuilder()
                    .AddJsonFile("loggerconfig.json")//mantained separate 
     config file.
                    .Build();
        Log.Logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(_config)
                    .CreateLogger();
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseSerilog()
            .UseStartup<Startup>();

根据Serilog,这是更好的方法。

答案 2 :(得分:0)

这是我如何从logging.json中读取的内容:

            var builder = new ConfigurationBuilder()
                .AddJsonFile(path: "logging.json", optional: false, reloadOnChange: true);

            var config = builder.Build();
            Log.Logger = new LoggerConfiguration()
                        .Enrich.With(new EventBusLogEnricher())
                        .ReadFrom.Configuration(config)
                        .CreateLogger();