How to set NLog's fileName to the process star

2019-04-08 04:23发布

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

2条回答
Lonely孤独者°
2楼-- · 2019-04-08 04:54

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" ) );
  • Note that error handling is not included, you should take care of it as you see fit.
查看更多
唯我独甜
3楼-- · 2019-04-08 05:11

Using the Cached Layout Renderer

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}"/>

Using a custom Layout Renderer

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.

查看更多
登录 后发表回答