在处理队列中的消息时,我想为每条消息跟踪多个参数-其ID,用户名等。
根据我的发现,MappedDiagnosticsLogicalContext.SetScoped
应该可以使用,是否可以同时设置多个键?此类字段的数量根据已知条件而有所不同,因此,我需要一个可以一次设置所有字段的助手。
不幸的是,当前的API不允许合成,因此以下尝试失败:
public static IDisposable SetContext(this Dictionary<string, string> fieldValues)
{
IDisposable result = null;
foreach (var pair in fieldValues)
{
result = MappedDiagnosticsLogicalContext.SetScoped(pair.Key, pair.Value);
}
return result;
}
此方法仅删除最后添加的键,所有先前的键都保留在其中。
SetScoped
方法的底层API是NLog的内部组件,因此我很难调用它们。
关于如何使其工作有任何建议吗?
答案 0 :(得分:2)
升级到NLog版本。 4.6.5将允许您使用此方法:
IDisposable MappedDiagnosticsLogicalContext.SetScoped(IReadOnlyList<KeyValuePair<string,object>> items);
您可以这样称呼它:
MappedDiagnosticsLogicalContext.SetScoped(fieldValues);
但是您的fieldValues必须为Dictionary<string, object>
类型