Mike
Mike

Reputation: 323

Customize threadName in .NET when using NLog

I'm currently using NLog to log out the threadName, but to use the threadId when there is no name.

This has worked well for a long time using the following format

${threadname:whenEmpty=${threadid}}

However, after upgrading to .NET 8 from .Net Framework, I see that Microsoft has decided to name all of the ThreadPool threads with the same name ".Net TP Worker", so it makes it hard to look a the logs and work out which thread things are happening on.

I see NLog has some other available "when" filtering functionality, but can't work out the correct way, if possible, to make log the threadId in both cases, where the threadName is empty, or if it matches ".Net TP Worker"

Upvotes: 0

Views: 20

Answers (1)

Rolf Kristensen
Rolf Kristensen

Reputation: 19877

I guess you can do this:

<nlog>
   <variable name="threadinfo" layout="${replace:inner=${threadname}:searchFor=.Net TP Worker:whenEmpty=${threadid}}" />
</nlog>

Then you can use ${threadinfo} instead of ${threadname}.

P.S. When using NLog ver. 5.1.1 (or older) then you might also need to specify replaceWith=. See also: https://github.com/NLog/NLog/wiki/Replace-Layout-Renderer

P.P.S. It is also possible to register a custom layoutrenderer. See also: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-layout-renderer

P.P.P.S. Guess NLog could improve the shorthand notation, so it becomes something like ${threadname:truncateWhen=.Net TP Worker:whenEmpty=${threadid}}

Upvotes: 0

Related Questions