Search code examples
c#nlog

How to get path of current target file using NLog in runtime?


I use NLog with next configuration:

  <targets>
    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
            layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="f" />
  </rules>

I tried to get FileName property of FileTarget (I check, that there only one FileTarget in collection)

NLog.LogManager.GetCurrentClassLogger().Info("test");
var logFile = (from t in NLog.LogManager.Configuration.AllTargets
                where t is NLog.Targets.FileTarget
                select (NLog.Targets.FileTarget)t).FirstOrDefault();

But logFile.FileName contains only pattern of file name, exactly how it's specified in settings.

How can I get in runtime path of current log file?


Solution

  • This did the trick for me:

    var fileTarget = LogManager.Configuration?.FindTargetByName<NLog.Targets.FileTarget>("file");
    string fileName = fileTarget?.FileName.Render(LogEventInfo.CreateNullEvent());
    if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
        throw new Exception("Log file does not exist.");