*** use WrapperLayoutRendererBase instead of LayoutRenderer, this blog post is about LayoutRenderer ***
NLog has lot of built-in layout renderers. Here is a list of official layout renderers:
https://nlog-project.org/config/?tab=layout-renderers
Creating custom layout renderer is very simple and straight-forward. Here is the official documentation:
https://github.com/NLog/readthedocs/blob/master/docs/How-to-write-a-custom-layout-renderer.md
There are 2 ways:
Lambda:
LayoutRenderer.Register("name", (logEvent, config) => "Message");
In the above scenarion, we can use ${name} when defining a layout, of course instead of returning static string we can do something useful based on the use-case.
Class:
Define a new class inherited from NLog.LayoutRenderers.LayoutRenderer. Use class attribute LayoutRenderer(“name”). LayoutRenderer is an abstract class, implement the class by overriding Append(StringBuilder builder, LogEventInfo logEvent) method i.e Append the value that needs to be added to the log by appending to the StringBuilder parameter.
[LayoutRenderer("Example")]
public class ExampleLayoutRenderer : NLog.LayoutRenderers.LayoutRenderer
{
public string Value { get; set; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append("Value");
}
}
Extra parameters can be passed and assigned as properties of the custom class.
[LayoutRenderer("example")]
public class ExampleLayoutRenderer : NLog.LayoutRenderers.LayoutRenderer
{
public string Value { get; set; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
// Your custom code
builder.Append(Value);
}
}
In the config file the custom layout renderer with params can be used like follows:
{example}
{example:value=abc}
Sometimes, in logs we write some data that might be needed for identifying but not necessarily the real value and for various reasons we might just need a hash. For example: SessionId / Some Cookie Value / IP address etc… Having a custom renderer for hashing such a value could be used.
Very few lines of code, i.e hashing and appending to a stringbuilder would solve the need i.e 2 – 3 lines of code. But, I think the 2 – 3 lines of code could be helpful for other people. I am considering creating an opensource version. I might or might not release nuget package. If I release nuget package, I would definitely make an anouncement. Anyway, not a big open-source project, but just few lines of code.
–
Mr. Kanti Kalyan Arumilli
B.Tech, M.B.A
Founder & CEO, Lead Full-Stack .Net developer
ALight Technology And Services Limited
Phone / SMS / WhatsApp on the following 3 numbers:
+91-789-362-6688, +1-480-347-6849, +44-07718-273-964
+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)
kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.