Reputation: 303
I have followed the https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer article to create a layout renderer. The hello-world example works find, but when I go it inject something it is not writting anything.
// 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>
I expect that the correlation should be coming through.
Upvotes: 0
Views: 825
Reputation: 36750
You need to override the CreateInstance
in NLog, so it could create the 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
};
Update:
If you registering is too late, you could queue a reload of all assemblies by NLog as follows:
ConfigurationItemFactory.Default = null; // (namespace NLog.Config).
It will be reloaded just before first usage of NLog
Upvotes: 1