Win4ster Win4ster - 6 days ago 7
C# Question

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?

Answer

This did the trick for me:

var fileTarget = (FileTarget) LogManager.Configuration.FindTargetByName("file");
// Need to set timestamp here if filename uses date. 
// For example - filename="${basedir}/logs/${shortdate}/trace.log"
var logEventInfo = new LogEventInfo {TimeStamp = DateTime.Now}; 
string fileName = fileTarget.FileName.Render(logEventInfo);
if (!File.Exists(fileName))
    throw new Exception("Log file does not exist.");