NLog如何写消息源

NLog how to write message source

我想记录调用log方法的class信息。

Logger Logger = LogManager.GetCurrentClassLogger();
Logger.Info("Start");

我想在日志中看到执行上述代码的 class 的完整 class 名称。

我在 NLog documentation 中看到提到了一个 source 选项,但不太清楚如何使用它以及它是否符合我的要求。

这是我想看到的:

2019-11-11 15:07:19.6935 DefaultLogger MyProject.Program INFO Start

其中 MyProject.Main 是呼叫 Logger.Info 的 class 的全名 class。

编辑:

这是我配置记录器的方式:

var config = new LoggingConfiguration();
var allLogs = new NLog.Targets.FileTarget("allLogs");
allLogs.Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}";
allLogs.FileName = basePath + "/${shortdate}.log";
config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, allLogs));
config.AddTarget(allLogs);

LogManager.Configuration = config;

callsite layout renderer 似乎符合您的要求:

The call site (class name, method name and source information).

头脑:"Not supported on NetStandard 1.3"

语法:

${callsite:className=Boolean:fileName=Boolean:includeSourcePath=Boolean:methodName=Boolean}

供您参考:关于可用的布局渲染器有一个很好的概述 here


顺便说一句:如果您使用 LogManager.GetCurrentClassLogger(), then the ${logger} 布局渲染器,将渲染创建记录器的 class 的完全限定 class 名称。

Gets the logger named after the currently-being-initialized class.