I tried
<target name="txtFile"
xsi:type="File"
fileName="${date:format=yyyy-MM-dd HH-mm-ss}.txt"
layout="${longdate} ${level} ${message}"/>
but it creates a new file each minute.
I realize that there is ${processinfo:property=StartTime}
but I couldn't format it. I tried:
${processinfo:property=StartTime:format=yyyy-MM-dd HH-mm-ss}
but it doesn't work
For a solution that doesn't require code, use the Cached Layout Renderer:
<target name="txtFile"
xsi:type="File"
fileName="${cached:cached=true:inner=${date:format=yyyy-MM-dd HH-mm-ss}}.txt"
layout="${longdate} ${level} ${message}"/>
The solution from above does not actually use the process start time. Instead, it uses the time when the first log message was routed to this target (e.g. first log to file). This can be a problem if, for example, you want the log files to reside in a directory that is named after the process start time.
In that case, a custom Layout Renderer may be used. Add the following class to your project:
namespace NLog.LayoutRenderers
{
using NLog.Config;
[LayoutRenderer("processstarttime")]
public class ProcessStartTimeLayoutRenderer : DateLayoutRenderer
{
private Process process;
protected override void InitializeLayoutRenderer()
{
base.InitializeLayoutRenderer();
this.process = Process.GetCurrentProcess();
}
protected override void CloseLayoutRenderer()
{
if (this.process != null)
{
this.process.Close();
this.process = null;
}
base.CloseLayoutRenderer();
}
protected override void Append(System.Text.StringBuilder builder, LogEventInfo logEvent)
{
if (this.process != null)
{
builder.Append(this.process.StartTime.ToString(this.Format, this.Culture));
}
}
}
}
And use it as follows:
<target name="txtFile"
xsi:type="File"
fileName="${processstarttime:format=yyyy-MM-dd HH-mm-ss}.txt"
layout="${longdate} ${level} ${message}"/>
This solution is based on the Process Info Layout Renderer.
The way I solve it is by hardening the filename from code.
Here's an example for your case:
FileTarget fileTarget =
LogManager.Configuration.AllTargets.
Where( t => t.Name == "txtFile" ).First() as FileTarget;
DateTime Now = DateTime.Now;
fileTarget.FileName =
string.Format( "{0}.txt", Now.ToString( "yyyy-MM-dd HH-mm-ss" ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With