我不确定,但我的猜测是NLog基于filename属性(因为您使用的是日期布局渲染器是动态的)检查日志文件的存在。因此,由于文件名称正在改变(即每次检索到文件名称时它都不同(或可能不同)),NLog会创建一个新文件。
尝试使用shortdate布局呈现这样的:
<targets>
<target name="logfile" xsi:type="File"
fileName="..\logs\${shortdate}_trg.log"
layout="${counter} | ${date:format=yyyy-MM-dd HH\:mm\:ss.ffff} | ${machinename} | ${level:uppercase=true} | ${logger:shortName=true} | ${stacktrace} | ${message:exceptionSeparator=EXCEPTION:withException=true}"
keepFileOpen="true"/>
</targets>
我想你会看到你的文件名不会改变(直到午夜)。
关键是NLog会一直检查文件是否存在(根据文件名为的值在写日志消息的时候),如果文件不存在,将会创建该文件。
或者,如果您想用更精确的文件名命名日志文件(即它是某个日期某个时间创建的),那么您可以将该时间存储在GlobalDiagnosticContext中并使用gdc布局呈现器来帮助命名文件。事情是这样的:
//Early in your program do something like this:
NLog.GlobalDiagnosticContext["StartTime"] = DateTime.Now.ToString("yyyyMMdd_HHmmss");
在你NLog.config文件,做这样的事情:
<targets>
<target name="logfile" xsi:type="File"
fileName="..\logs\${gdc:item=StartTime}_trg.log"
layout="${counter} | ${date:format=yyyy-MM-dd HH\:mm\:ss.ffff} | ${machinename} | ${level:uppercase=true} | ${logger:shortName=true} | ${stacktrace} | ${message:exceptionSeparator=EXCEPTION:withException=true}"
keepFileOpen="true"/>
</targets>
最后,你可以写一个自定义LayoutRenderer来填充的日期/时间。它会得到一次,然后每次都返回相同的值。
这将是这个样子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Globalization;
using NLog;
using NLog.Config;
using NLog.LayoutRenderers;
namespace MyNLogExtensions
{
[LayoutRenderer("StartTime")]
class StartTimeLayoutRenderer : LayoutRenderer
{
private DateTime start = DateTime.Now;
public StartTimeLayoutRenderer()
{
this.Format = "G";
this.Culture = CultureInfo.InvariantCulture;
}
//
// In NLog 1.x, LayoutRenderer defines a Culture property.
// In NLog 2.0, LayoutRenderer does not define a Culture property.
//
public CultureInfo Culture { get; set; }
[DefaultParameter]
public string Format { get; set; }
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(start.ToString(this.Format, this.Culture));
}
protected override int GetEstimatedBufferSize(LogEventInfo logEvent)
{
return 10;
}
}
}
在你NLog.config文件,你需要这样的事要告诉您的扩展名是:
<extensions>
<add assembly="MyAssembly.dll"
</extensions>
然后你的目标配置,看起来像这样:
<targets>
<target name="logfile" xsi:type="File"
fileName="..\logs\${StartTime:format=yyyyMMdd_HHmmss}_trg.log"
layout="${counter} | ${date:format=yyyy-MM-dd HH\:mm\:ss.ffff} | ${machinename} | ${level:uppercase=true} | ${logger:shortName=true} | ${stacktrace} | ${message:exceptionSeparator=EXCEPTION:withException=true}"
keepFileOpen="true"/>
</targets>
尝试此链接: http://www.sharedcache.com/cms /configuration_nlog.aspx – 2011-11-07 08:24:18