Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding properties to log message in NLog in .net core

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?

like image 372
Purnima Naik Avatar asked Jan 31 '17 12:01

Purnima Naik


People also ask

Does NLog work with .NET Core?

nuget.org/packages/NLog/… NLog 4.7 has been released! See news post: nlog-project.org/2020/03/28/nlo… While older versions of NLog works well on ASP.NET Core 3, we have optimized the NLog.

How do I edit NLog config file?

You can find the NLog. config file in {Project Folder}\bin\Debug\net5. 0\ . You can open and edit it as you like with Notepad or Visual Studio.


1 Answers

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.

like image 60
truemedia Avatar answered Nov 01 '22 10:11

truemedia