How can I query the path to an NLog log file?

十年热恋 提交于 2019-12-09 15:20:20

问题


I've configured a file target for NLog as follows:

<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>

How can I query the actual filesystem path (fileName) of this File target via NLog's API?


回答1:


I've just tried to get this information via the configuration api.

Sadly it looks like the configuration is evaluated by the actual target and is not resolved in the configuration.

As {basedir} refers to the appdomain base directory you could simply read this value on your own.

var basedirPath = AppDomain.CurrentDomain.BaseDirectory;



回答2:


    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 });
    }



回答3:


You could use nLog's api inside of code instead of an xml configuration file. Then, in your application, you assign the log's file path to a variable, and use that variable as the target's filename. You can access that variable, OR change it anytime you like (my snippet, here, is defined inside of a class).

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


来源:https://stackoverflow.com/questions/7332393/how-can-i-query-the-path-to-an-nlog-log-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!