gpt4 book ai didi

c# - 如何将 processid 添加到 log4net 布局?

转载 作者:行者123 更新时间:2023-11-30 14:45:28 25 4
gpt4 key购买 nike

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

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

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

我在 log4net 官方网站的常见问题解答部分找到了 following message:

The following example sets the file name for a FileAppender to include the current process id by specifying the %processid pattern in the File property.

<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

最佳答案

您可以实现自定义 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>

关于c# - 如何将 processid 添加到 log4net 布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53445478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com