Reputation: 3590
Specifying message format via declarative layout string is a easy way but only in simple cases.
When I see conditions or nested layouts I want to use plain code to format my message.
How can I format my messages via plain code?
Upvotes: 0
Views: 619
Reputation: 19867
You can also create your own custom Layout-class:
class CustomLayout : Layout
{
protected string GetFormattedMessage(LogEventInfo logEvent)
{
// Legacy-style
return "King of the world";
}
protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
// New style supports reusable StringBuilder (reduces allocation)
target.Append(GetFormattedMessage(logEvent));
}
}
Upvotes: 1
Reputation: 19867
You can always register your own custom layout renderer that generates whatever wonderful pattern you like:
LayoutRenderer.Register("king", (logEvent) => "King of the World");
Just make sure to register the layout before loading the NLog-config (or creating any NLog-Logger objects, including static Logger-objects).
Then you can use your custom-layoutrenderer in the Layout like normal (Ex. ${king}
)
See also: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer
See also: https://nlog-project.org/documentation/v4.5.0/html/T_NLog_LogEventInfo.htm (Available logevent
-properties)
Upvotes: 2