我已经按照https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer文章创建了布局渲染器。 hello-world示例可以找到,但是当我进行注入时,它并没有写任何东西。
// NOTE: ICorrelationContextAccessor is part of the CorrelationId nuget package
[LayoutRenderer("correlation-id")]
public class CorrelationIdLayoutRenderer : LayoutRenderer
{
private readonly ICorrelationContextAccessor _correlationContext;
public CorrelationIdLayoutRenderer(ICorrelationContextAccessor correlationContext)
{
_correlationContext = correlationContext;
}
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var correlation = _correlationContext.CorrelationContext.CorrelationId;
builder.Append(correlation);
}
}
nlog.config
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
<add assembly="[[ My assembly is here]]"/>
</extensions>
<targets>
<target xsi:type="File" name="ownFile-web" fileName="[[PATH]]/nlog-own-${shortdate}.log"
layout="${longdate}|${level:fixedLength=True:padding=5:padCharacter= :upperCase=True}|${correlation-id}|${message} ${exception:format=tostring}" />
</targets>
我希望相关性能够实现。
答案 0 :(得分:1)
您需要在NLog中覆盖CreateInstance
,以便它可以创建CorrelationIdLayoutRenderer
ConfigurationItemFactory.Default.CreateInstance = (Type type) =>
{
// your custom target.
if(type == typeof(CorrelationIdLayoutRenderer))
return new CorrelationIdLayoutRenderer(...); // TODO get ICorrelationContextAccessor
else
return Activator.CreateInstance(type); //default
};
更新:
如果注册太晚,可以通过NLog将所有程序集的重新加载排队,如下所示:
ConfigurationItemFactory.Default = null; // (namespace NLog.Config).
它将在第一次使用NLog之前重新加载