【问题标题】:Azure Function requires hosts.json logging for Serilog to work in log streamAzure Function 需要 hosts.json 日志记录,以便 Serilog 在日志流中工作
【发布时间】:2021-06-09 13:45:44
【问题描述】:

我有这个代码设置来配置 Serilog:

    public static IFunctionsHostBuilder AddLogger(this IFunctionsHostBuilder builder, string applicationName)
    {
        builder.Services.SetupLogging(applicationName);
        return  builder;
    }
    
    
    public static void SetupLogging(this IServiceCollection services, string applicationName)
    {
        var logger = CreateLogger(applicationName);
        services.AddLogging(lb =>
        {
            lb.AddSerilog(logger);
        });
    }

    public static Logger CreateLogger(string applicationName)
    {
        
        var instrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
        
        return new LoggerConfiguration()
            .MinimumLevel.Information()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)  
            .Enrich.FromLogContext()
            .Enrich.WithProperty("Application", applicationName)
            .Enrich.WithCorrelationIdHeader(Constants.CorrelationIdHeader)
            .WriteTo.Console()
            .WriteTo.ApplicationInsights(new TelemetryConfiguration(instrumentationKey), TelemetryConverter.Traces)
            .CreateLogger();
    }

然后我将ILogger<MyClass> 注入到我的函数类中,然后我执行logger.LogInformation("test"),一切都很好。

但是,我注意到我需要 hosts.json 包含以下内容,以便日志出现在 Azure 门户日志流中。奇怪的是,App Insights 包含 hosts.json 是否包含以下数据。控制台日志似乎不遵守 Serilog 配置并依赖于 hosts.json。

任何人都可以解释这一点并让它在不需要填充 hosts.json 的情况下工作

  "logging": {
    "logLevel": {
      "default": "Information"
    }
  }

【问题讨论】:

    标签: c# azure azure-functions serilog


    【解决方案1】:

    只需在您的 SetupLogging 方法中配置

    builder.Services.AddSingleton<ILoggerProvider>(sp => new SerilogLoggerProvider(Log.Logger, true));
    
    builder.Services.AddLogging(lb => lb.AddSerilog(Log.Logger, true));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多