如何记录自定义变量

How to log custom variables

我想记录请求持续时间。为此,我有一个中间件,在 OnActionExecuted 上,我将经过的时间分配给一个变量,并尝试使用 Custom Layout Rendere through a lambda function

注册它
requestDuration = _stopWatch.ElapsedMilliseconds;
LayoutRenderer.Register("requestDuration", logEvent => requestDuration);

在我的 nlog.config 上,我有以下

<column name ="RequestDuration" layout="${requestDuration}" quoting="Nothing"/>

NLog 抱怨说这将被忽略:

Error Error parsing layout requestDuration will be ignored. Exception: System.ArgumentException: LayoutRenderer cannot be found: 'requestDuration'
   at NLog.Config.Factory`2.CreateInstance(String itemName)
   at NLog.Layouts.LayoutParser.GetLayoutRenderer(ConfigurationItemFactory configurationItemFactory, String name)

我是不是在错误的地方注册了layoutRenderer?

请注意,我正在尝试使用请求持续时间列,而不是简单地将时间写在日志消息中

如果您在注册布局渲染器时得到 "LayoutRenderer cannot be found",那么 NLog 会在布局注册之前解析配置。

你可以在注册后做一个reinitialize:

LogManager.Configuration = LogManager.Configuration.Reload();

虽然越早注册越好。

请注意,对于这种情况,似乎并不真正需要自定义布局渲染器。有很多上下文选项,请参阅 https://github.com/NLog/NLog/wiki/Context