'NLog: Format loglevel with Whitespaces

I am using NLog for logging. Currently my Layout-String is:

"${date:format=dd.MM.yyyy HH\\:mm\\:ss,fff} | ${level:uppercase=true} | ${message}"

This results in the following Logs:

18.12.2013 11:23:14,834 | INFO | this is an info
18.12.2013 11:23:14,835 | TRACE | this is a trace

What I want now is to format the "$level" to fill up with Whitespaces so that it looks like a table with 5 Characters.

I would like to have:

18.12.2013 11:23:14,834 | INFO  | this is an info
18.12.2013 11:23:14,835 | TRACE | this is a trace

I didn't find anything sadly... Can anyone help?



Solution 1:[1]

Try using the PaddingLayoutRendererWrapper. I'm not sure where a good config example is, but the source in NLog's source repository is located here, so maybe you can reverse engineer the correct configuration:

https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/Wrappers/PaddingLayoutRendererWrapper.cs

I think you would do something like this:

"${date:format=dd.MM.yyyy HH\\:mm\\:ss,fff} | ${padding:padding=5,fixedlength=true:${level:uppercase=true}} | ${message}"

Hopefully, that example will pad all log level values with 5 spaces on the left and then trim to an absolute length of 5.

padding=5 means to add 5 padcharacters (default is ' ') to left (negative means pad on right)

fixedlength=true is a boolean that indicates that the padded result should be trimmed to a maximum length of "padding" (i.e. 5 in my example)

Solution 2:[2]

As of 2022, use the following:

${level:uppercase=true:padding=-5}

Example:

2022-04-15 03:04:58.0764 | INFO  | Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler | AuthenticationScheme: Cookies was challenged.

If you want to align right, use 5 instead of -5.

Reference: https://github.com/NLog/NLog/wiki/Pad-Layout-Renderer

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 stil