Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include logging scope into the log file using NLog

I'm using NLog.Extensions.Logging.

When registering a logger factory using the method AddNLog(), it is possible to enable logging scope using NLogProviderOptions.IncludeScopes.

But how to make NLog write logging scope to a file?

I haven't found anything similar in the list of available layouts

like image 710
Sergun Avatar asked Feb 20 '20 17:02

Sergun


People also ask

How do I store log in database using NLog?

To start logging, we need to create a Logger instance. Before creating the Logger instance, we are configuring Nlog by passing the configuration file nlog. config which we are going to create in the next section. The GetCurrentClassLogger() method returns the Logger instance with the name of the current class (Nlog.

How do I add a NLog config to a project?

Adding NLog NuGet Package As a first step we need to install NLog from NuGet package manager. To do this, right click the Project from Solution Explorer and select Manage NuGet Packages from the context menu. It will open the Package Manager Solution window. From the Package Manager window, browse for NLog.


1 Answers

An example:

Log like this:

// logger is here of type Microsoft.Extensions.Logging.ILogger
using (logger.BeginScope(new[] { new KeyValuePair<string, object>("userid", request.UserId) }))
{
   logger.LogDebug("My log message");
}

Render like this: ${mdlc:userid}.

For example in the file target:

 <target name="file" xsi:type="File"
     layout="${longdate} ${logger} ${message}${exception:format=ToString}, user: ${mdlc:userid}" 
     fileName="${basedir}/${shortdate}.log" />

Note: NLogProviderOptions.IncludeScopes is enabled by default.

NLog directly

The syntax is a bit clumsy, but that is because Microsoft's abstraction is a bit limited. See also this issue: .NET - Logging structured data without it appearing in the text message

If you refer NLog directly, you could also do:

using (NLog.MappedDiagnosticsLogicalContext.SetScoped("userid", request.UserId))
{
   // logger here of type NLog.Logger
   logger.Info("My log message");
}

Also this is rendered with ${mdlc:userid}

More examples and different scopes for NLog explained here

Docs

PS: I have updated available layouts, so you could find it easier :)

enter image description here

like image 189
Julian Avatar answered Nov 03 '22 00:11

Julian