【问题标题】:.Net Core 3.1 - Set ForContext for Serilog with Microsoft Ilogger interface.Net Core 3.1 - 使用 Microsoft Ilogger 界面为 Serilog 设置 ForContext
【发布时间】:2022-11-02 01:43:49
【问题描述】:

如何使用来自Microsoft.Extensions.LoggingILogger 接口将ForContext 方法用于Serilog 记录器?

这是代码:

private readonly ILogger<UserService> _logger;

//DI code here

....

//inside some method
_logger.ForContext("CorrelationId", correlationId); // Ilogger doesn't contain ForContext extension method 

_logger.LogInformation("message");

我真的不想使用 Serilog 中的 ILogger 接口,因为我不希望它是特定于 Serilog 的,而且它不是通用的。

【问题讨论】:

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


    【解决方案1】:

    ForContext 与 Microsoft.Extension.Logging

    微软记录器接口没有 ForContext 属性,但是,根据我可以在该主题上找到的几个读数,传递附加上下文信息的正确方法是使用它的 BeginScope 方法来传递值字典,然后调用您的 Logging 方法。

    using (logger.BeginScope(new Dictionary<string, object> {{ "ParameterName", 999 }}))
    {
        logger.LogInformation("This log entry and any other ones wrapped within this using statement will have context added similar to .ForContext with Serilog");
    }
    

    在 ILogger 上使用扩展方法

    我发现自己更喜欢为此目的编写扩展方法以避免使用{}当我想将上下文信息添加到结构化日志记录时,到处都是语句,并使我的代码中的意图更加清晰:

            public static void LogWithContext(this ILogger logger, Action LogAction, params KeyValuePair<string,object>[] contextDataParam)
            {
                Dictionary<string, object> contextData = new Dictionary<string, object>();
                foreach (KeyValuePair<string,object> kvp in contextDataParam)
                {
                    contextData.TryAdd(kvp.Key, kvp.Value);
                }
    
                using (logger.BeginScope(contextData))
                {
                    LogAction.Invoke();
                };
    
            }
    

    这可以这样调用:

    logger.LogWithContext(
        () => logger.LogError("Error with {Database}",_options.database),
            new KeyValuePair<string, object>("CallingFunction", nameof(thisFunction)),
           new KeyValuePair<string, object>("UserErrorType", "DB")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-06
      • 2014-07-01
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      相关资源
      最近更新 更多