How do I get the name of the file NLog is writing to?
I am writing an application that will be utilized by members of our operations group. I'd like to show on the screen, the name of the file that NLog is writing to. This will allow them to view the file if necessary.
I could hard code the name, but I'd like t开发者_如何学Pythono allow the NLog.config file to be used instead. I'd like to be able to get the actual name of the file being written to.
Between a few comments I found on the internet and reflecting on the assembly with Telerik JustDecompile, I was able to come up with this solution.
When I need the actual name of one of my targets, I can just call the method below like this
string fileName = GetLogFileName("file");
where file is the name of my target in the nlog.config file
public string GetLogFileName(string targetName) {
string rtnVal = string.Empty;
if (LogManager.Configuration != null && LogManager.Configuration.GetConfiguredNamedTargets().Count != 0) {
Target t = LogManager.Configuration.FindTargetByName(targetName);
if(t != null){
Layout layout = new Layout((t as NLog.Targets.FileTarget).FileName);
rtnVal = layout.GetFormattedMessage(null);
}
}
return rtnVal;
}
for the 2.1.0.0 release of NLog, I've had to change the code to this
public string GetLogFileName(string targetName) {
string rtnVal = string.Empty;
if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0) {
NLog.Targets.Target t = LogManager.Configuration.FindTargetByName(targetName);
if (t != null) {
NLog.Layouts.Layout layout = (t as NLog.Targets.FileTarget).FileName;
rtnVal = layout.Render(LogEventInfo.CreateNullEvent());
}
}
return rtnVal;
}
you need to write a custom target
follow the instructions under nlog-project.org/wiki/How_to_write_a_Target
then modify it to be an interceptor only and add the ActualLogfile property
[Target("Interceptor")]
public sealed class InterceptTarget : FileTarget
{
public string ActualLogfile { get; set; }
protected override void Write(LogEventInfo logEvent)
{
ActualLogfile = this.FileName.Render(logEvent);
string logMessage = this.Layout.Render(logEvent);
base.Write(logEvent);
}
}
NLog.config should be something like this:
<nlog>
<targets>
<target name="i"
xsi:type="Interceptor"
fileName="${basedir}\logs\${shortdate}.log" />
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="i"/>
</rules>
</nlog>
remark: be shure to generate a very early log message (at pgm start), before ActualLogFile is empty.
Why not simply parse NLog.config for any/all <target>'s?
精彩评论