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