首页 > 解决方案 > 如何将多个变量从方法传递到 NLOG.config?

问题描述

目前我在一个方法中有两个变量,

float processTime = processTime.ElapsedMilliseconds;
var rowsTotal = resultadoSQL.Rows.Count;

我想将这两个变量传递给 NLog.config,所以我可以像这样使用它们:

<target name="sql" xsi:type="File" fileName="C:\Users\Dev\Desktop\Framework\Logs\sql.txt" 
        layout="'Rows count:' (rowsTotal) 'Elapsed Time:' processTime"/>

显然布局中的语法是错误的,他的目的只是为了展示我想要实现的目标。.txt 文件如下所示:

行数:456 经过时间:87878

标签: c#nlog

解决方案


也许将目标布局更改为${message}并执行以下操作:

logger.Info($"'Rows count:' {rowsTotal} 'Elapsed Time:' {processTime}");

您还可以更高级并使用 NLog LogEvent 属性:

https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer

如果使用 NLog 4.5,那么您可以使用结构化日志记录:

https://github.com/NLog/NLog/wiki/How-to-use-structured-logging

您还可以使用 NLog Fluent API:

https://github.com/NLog/NLog/wiki/Fluent-API

或者直接将属性写入NLog.LogEventInfo.Properties


推荐阅读