如何查询 NLog 日志文件的路径?

10

我已经配置了一个 NLog 的文件输出目标,配置如下:

<targets>
  <target name="asyncFile" xsi:type="AsyncWrapper">
    <target xsi:type="File" name="logfile" fileName="${basedir}/Logs/${shortdate}.log"
          layout="${longdate} ${uppercase:${level}} ${message}" />
  </target>    
</targets>

我如何通过 NLog 的 API 查询此 File 目标的实际文件系统路径 (fileName)?


你的需求是什么?为什么需要知道路径? - ccellar
3
很有趣,因为我并不确定${basedir}会被解析成什么。 - aknuds1
4个回答

11
    private string GetLogFile()
    {
        var fileTarget = LogManager.Configuration.AllTargets.FirstOrDefault(t => t is FileTarget) as FileTarget;
        return fileTarget == null ? string.Empty : fileTarget.FileName.Render(new LogEventInfo { Level = LogLevel.Info });
    }

像魔法一样运作! - Kevin Marshall

9
我刚刚尝试通过配置API获取此信息。

enter image description here

很遗憾,配置似乎由实际目标评估,并且不在配置中解决。
由于{basedir}指的是应用程序域基目录,因此您可以自行读取此值。
var basedirPath = AppDomain.CurrentDomain.BaseDirectory;

0
你可以在代码中使用nLog的API而不是XML配置文件。然后,在你的应用程序中,将日志文件路径分配给一个变量,并将该变量用作目标文件名。你可以随时访问该变量或更改它(我的片段在这里定义在一个类中)。
Private MainNlogConfig As New LoggingConfiguration()
Dim localrule As New LoggingRule(*, LogLevel.Info, locallogtarget)
MainNlogConfig..AddTarget("file", locallogtarget)

With locallogtarget
    .Layout = "${longdate} ${logger} ${message}"
    .FileName = appdir & appName & ".log"  '----->LOOK HERE!
End With
LogManager.Configuration = MainNlogConfig

0
你可以查找FileTarget并像这样解析文件名:
var fileTarget = LogManager.Configuration?.FindTargetByName<NLog.Targets.FileTarget>("logfile");
string filePath = fileTarget?.FileName.Render(LogEventInfo.CreateNullEvent());
string directory = System.IO.Path.GetDirectoryName(filePath);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接