簡體   English   中英

Serilog中如何根據開發環境將日志寫入特定的sink?

[英]How to write logs to a specific sink depending on the developement environment in Serilog?

我將 Serilog 與 Azure Functions v4 和 .NET 7 一起使用。我正在嘗試將日志寫入本地控制台和 Application Insights。 我已經花了幾個小時嘗試不同的解決方案,在撰寫本文時的情況似乎是這個技術堆棧(Azure Functions + Application Insights)不成熟或太新,而且還沒有很好的記錄。

按環境設置appsettings.{env}.json文件並嘗試按環境添加不同的 Serilog 配置不適用於 Azure 函數。 根據我嘗試的解決方案,要么使用 Microsoft 記錄器,要么沒有日志。

下面的代碼適用於控制台,但我在 Application Insights 上得到了重復的日志。 如果我刪除 Console sink,它在 Application Insights 中運行良好,但我沒有更多的本地日志:

.UseSerilog((hostBuilderContext, serviceProvider, loggerConfiguration) =>
    loggerConfiguration
        .MinimumLevel.Debug()
        .WriteTo.Console()
        .WriteTo.ApplicationInsights(
            serviceProvider.GetRequiredService<TelemetryConfiguration>(),
            TelemetryConverter.Traces)
)

我還嘗試了其他設置記錄器的方法,例如在 .ConfigureServices .ConfigureServices(...中,在 function 代碼中以不同的方式注入它,但沒有運氣。許多示例討論了我沒有的Startup方法。如果它有幫助我可以在此處發布整個Program.cs和 function 代碼。

所以我現在添加.Enrich.WithEnvironmentName()以從環境變量中獲取環境名稱,問題是:如何在上面的代碼(不是配置文件)中使用ByIncludingOnly過濾日志以根據環境名稱包含日志( LocalDevelopment )? ByExcluding的相同問題 - 我想答案會相似。

這是做到這一點的方法。 我最終沒有使用 Environment enricher,因為在撰寫本文時它不支持 Azure 函數 ( AZURE_FUNCTIONS_ENVIRONMENT ) 的 Azure 環境變量。 看到這個問題:

https://github.com/serilog/serilog-enrichers-environment/issues/49

這就是我如何工作的:

豐富日志事件的第一個選項:

// Careful: Serilog is not able to enrich with the value of this variable and will default to 'Production'

var value = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") ?? "Development";
var predicate = $"EnvironmentName = 'Local'";

Log.Logger = new LoggerConfiguration()
    .Enrich.WithProperty("EnvironmentName", value)
    .MinimumLevel.Debug()

    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(predicate)
        .WriteTo.Console(outputTemplate: "{Properties} {Message}"))

    .WriteTo.Logger(lc => lc
        .WriteTo.File(path: Directory.GetCurrentDirectory() + @"\test.txt"))
    
    .CreateLogger();

不豐富日志事件的第二個選項:

var value = Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT") ?? "Development";
var predicate = $"{value} = 'Local'";

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()

    .WriteTo.Logger(lc => lc
        .Filter.ByIncludingOnly(predicate)
        .WriteTo.Console(outputTemplate: "{Properties} {Message}"))

    .WriteTo.Logger(lc => lc
        .WriteTo.File(path: Directory.GetCurrentDirectory() + @"\test.txt"))
    
    .CreateLogger();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM