Adding properties to log message in NLog in .net core

Purnima Naik picture Purnima Naik · Jan 31, 2017 · Viewed 9.3k times · Source

I am using NLog for logging messages in .net core.

I have added NLog in StartUp.cs as follows:

loggerFactory.AddNLog();

For logging to file, I am using following method:

logger.LogInformation("Message");

I want to add custom NLog event properties to my message. But LogInformation() is not allowing me to pass that. How can I do that?

Answer

truemedia picture truemedia · Feb 1, 2017

If you want custom layout properties (NLog calls them layout renderers) you can use the EventProperties Layout Renderer. You can simply do this in your code:

var logger = LogManager.GetCurrentClassLogger();
var eventInfo = new LogEventInfo(LogLevel.Info, logger.Name, "Message");
eventInfo.Properties["CustomValue"] = "My custom string";
eventInfo.Properties["CustomDateTimeValue"] = new DateTime(2020, 10, 30, 11, 26, 50);
// You can also add them like this:
eventInfo.Properties.Add("CustomNumber", 42);
// Send to Log
logger.Log(eventInfo);

Then you will be able to add these (any any properties you make up) in your nlog.config

<target>
  <parameter name="@customtime" layout="${event-properties:CustomDateTimeValue:format=yyyy-MM-dd HH\:mm\:ss}" />
  <parameter name="@customvalue" layout="${event-properties:item=CustomValue}" />
  <parameter name="@customnumber" layout="${event-properties:item=CustomNumber}" />
</target>

When using NLog with AspNetCore, it's useful to add the NLog.Web Package for ASP.NET Core which gives you many predefined Layout renderers. You can find more about NLog.Web for AspNetCore on their Github page.

This AspNetCore package will give you things like the following:

<parameter name="@UserName" layout="${aspnet-user-identity}" />
<parameter name="@MvcAction" layout="${aspnet-MVC-Action}" />
<parameter name="@Session" layout="${aspnet-session:Variable=User.Name:EvaluateAsNestedProperties=true}" />
... etc

You will find the complete list on the NLog.Web.AspNetCore Github page.