我已经按照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>
我希望相关性能够实现。
您需要覆盖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之前重新加载