Win4ster Win4ster - 4 months ago 56
C# Question

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

I use NLog with next configuration:

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

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

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?


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.");