【问题标题】:How to log custom variables如何记录自定义变量
【发布时间】:2019-08-09 10:26:26
【问题描述】:

我想记录请求持续时间。为此,我有一个中间件,在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?

请注意,我试图有一个请求持续时间的列,而不是简单地在日志消息上写下那个时间

【问题讨论】:

    标签: c# asp.net-core nlog


    【解决方案1】:

    如果您在注册布局渲染器时收到“找不到布局渲染器”,则 NLog 在布局注册之前解析了配置。

    你可以在注册后做一个reinitialize

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

    虽然早点注册更好。

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

    【讨论】:

    • 这不是意味着每当应用程序通过中间件时,它都会重新加载配置吗?目前正在探索LogEvent Properties Dictionary
    • 只有在您编辑配置文件(并启用自动重载)或显式调用时才会重新加载。注册布局渲染器后不会自动重新加载
    • 如果您不执行太多次(例如每条日志消息),重新加载 NLog 配置并没有什么不好。希望这能回答你的问题
    • 在这种情况下,它会在每次进入中间件时重新加载(我想)。无论哪种方式,感谢您的链接(我以前读过它,但又去了那里), MappedDiagnosticsLogicalContext 完全符合我的需要。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多