如何使用NLog将日志记录作用域包括到日志文件中 [英] How to include logging scope into the log file using NLog

查看:740
本文介绍了如何使用NLog将日志记录作用域包括到日志文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NLog.Extensions.Logging.

使用方法AddNLog()注册记录器工厂时,可以使用NLogProviderOptions.IncludeScopes启用记录范围.

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

但是如何使NLog将日志记录作用域写入文件?

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

可用布局

推荐答案

示例:

这样登录:

// 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");
}

渲染如下:${mdlc:userid}.

例如在文件目标中:

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

注意:NLogProviderOptions.IncludeScopes默认情况下处于启用状态.

Note: NLogProviderOptions.IncludeScopes is enabled by default.

语法有点笨拙,但这是因为Microsoft的抽象有点受限制.另请参见以下问题: .NET-记录结构化数据而文本消息中不出现

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

如果直接引用NLog,也可以执行以下操作:

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");
}

这也可以用${mdlc:userid}

此处

PS:我已经更新了可用布局,这样您会发现它更容易:)

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

这篇关于如何使用NLog将日志记录作用域包括到日志文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆