How to include logging scope into the log file using NLog

雨燕双飞 提交于 2020-04-07 04:27:34

问题


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


回答1:


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 :)



来源:https://stackoverflow.com/questions/60325753/how-to-include-logging-scope-into-the-log-file-using-nlog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!