Nlog日志记录方法

本文关键字:方法 记录 日志 Nlog | 更新日期: 2023-09-27 18:24:00

我正处于一个小型网站开发项目的alpha阶段,并决定使用NLog作为我的日志记录解决方案。

到目前为止,我的解决方案是在没有日志记录的情况下开发的。我现在正在日志中添加。

一个例子:

private static Logger logger = LogManager.GetCurrentClassLogger();
public int SaveProject(ProjectDto project)
{
    logger.Trace("SaveProject ({0}) : {1}", project.Id, _userId);
    return _pb.SaveProject(project);
}

"GetCurrentClassLogger"方法非常棒,因为它现在知道我在哪个类中

但是,有没有一种方法可以报告方法名称,而不是我是如何进行的?在上面的示例中,您可以看到我需要将"SaveProject"添加到消息中。有没有办法自动得到这个?或者我需要将其添加到每个方法日志调用中吗?

Nlog日志记录方法

是的,请参阅callsite布局渲染器。您将其放入布局配置中。例如:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
        <target name="console" xsi:type="ColoredConsole" layout="${callsite:className=false:includeSourcePath=false:methodName=true} ${message}"/>
    </targets>
    <rules>
        <logger name="*" minlevel="Trace" writeTo="console" />
    </rules>
</nlog>