如何设置NLOG的文件名,进程开始日期? [英] How to set NLog's fileName to the process start date?

查看:1385
本文介绍了如何设置NLOG的文件名,进程开始日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过

<target name="txtFile"
        xsi:type="File"
        fileName="${date:format=yyyy-MM-dd HH-mm-ss}.txt"
        layout="${longdate} ${level} ${message}"/>

但它会创建一个新的文件中的每一分钟。 我意识到有 $ {processinfo:属性=开始时间} ,但我无法格式化。我想:

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

推荐答案

对于不需要code,使用缓存解决方案布局渲染

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 (i.e. first log to file). This can be a problem if, for example, you want 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));
            }
        }
    }
}

和使用它,如下所示:

<target name="txtFile"
    xsi:type="File"
    fileName="${processstarttime:format=yyyy-MM-dd HH-mm-ss}.txt"
    layout="${longdate} ${level} ${message}"/>

此溶液是基于<一href="https://github.com/NLog/NLog/blob/master/src/NLog/LayoutRenderers/ProcessInfoLayoutRenderer.cs"相对=nofollow>进程信息布局渲染。

这篇关于如何设置NLOG的文件名,进程开始日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆