我不確定,但我的猜測是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