【问题标题】:How to add processid to log4net layout?如何将 processid 添加到 log4net 布局?
【发布时间】:2019-04-25 23:52:26
【问题描述】:

我将在我的wpf 应用程序中使用log4net。我需要的日志中的消息如下所示:

11/8/2018 10:49:38 AM   13 (5368)       properties disabled.

其中13 是写此消息的processId。所以这很容易。但不幸的是,我无法做到这一点。所以我只需要为我的log4net 记录器设置一个合适的模式布局。

我在log4net官方网站的faq部分找到了following message

以下示例将FileAppender 的文件名设置为包含 通过在 文件属性。

<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
    <file type="log4net.Util.PatternString" value="log-file-[%processid].txt" />
    <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>

所以它有效,但仅适用于文件名而不适用于我的日志文件中的布局。我需要把这个%processid 放到我的布局中。而我目前的布局是:

<layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{dd/MM/yyyy HH:mm:ss,fff tt} %processid (%thread) - %message%newline" />
</layout>

我的日志只是将processid 字符串写入我的日志文件。

22/11/2018 16:21:51,863 PM processid (1) - Exiting application.

我还找到SO answer。它有效。但是%processid 属性在启动过程中只初始化一次。在我的应用程序中写作过程经常发生变化。所以这个解决方案不适合我。而且我猜默认可以实现log4net布局设置。

另一个选项是使用type="log4net.Util.PatternString" 作为我的conversionPattern 的一种类型。但它也不适合(如果我使用这种类型 - type="log4net.Util.PatternString" - 在 conversionPattern 中,那么 %threadId%level 甚至 %message 将被打印为字符串常量)。

23/11/2018 16:22:52,456 PM 31560 [thread] level - message

但我需要 %threadId%processid 在日志中。

【问题讨论】:

  • @pfx 实际上它不是重复的。我原来的问题有一个指向那个 SO 答案的链接以及为什么它不适合我的解释。我的目的有点不同。%processid 必须打印在我的日志文件中的每一行。它应该与其他参数一起打印(%threadId%level 等)。所以type="log4net.Util.PatternString" 也不适合(如果我使用这种类型 - type="log4net.Util.PatternString" - 在conversionPattern %threadId,@987654356 @将被打印为字符串常量)。所以我在日志中需要%threadId%processid%processid 在运行时会发生变化)
  • @pfx 很好,谢谢
  • 你能对你的问题做一个小的编辑吗?没有它,我无法删除标志
  • @pfx 我刚刚做了一些改动
  • 你可以尝试使用ThreadContext而不是GlobalContext log4net.ThreadContext.Properties["pid"] = Process.GetCurrentProcess().Id; 允许每个线程有不同的属性值。

标签: c# .net logging log4net log4net-configuration


【解决方案1】:

您可以实现自定义PatternLayoutConverter,它会输出进程 ID。
这样做,您不必设置和跟踪正在运行的进程的 Id。

namespace PFX
{
    class ProcessIdPatternLayoutConverter : PatternLayoutConverter
    {
        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            Int32 processId = Process.GetCurrentProcess().Id;
            writer.Write(processId);
        }
    }
}

然后,您可以在您的 Log4netconfig 中通过其完全限定的程序集名称引用此 PatternLayoutConverter,如下所示。

<layout type="log4net.Layout.PatternLayout">                        
    <converter>
        <name value="processid" />
        <type value="PFX.ProcessIdPatternLayoutConverter, PFX.Lib" />
    </converter>            
    <conversionPattern value="%date{dd/MM/yyyy HH:mm:ss,fff tt} %processid (%thread) - %message%newline" />
</layout>

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    相关资源
    最近更新 更多