vb.net Log4Net 在日志中打印“ThreadID”和“Thread Name”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42675024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Log4Net printing "ThreadID" and "Thread Name" in the log
提问by Denis
In our apps we usually name the threads that we create. For example, we would create a thread and give it a name like "WorkerThread".
在我们的应用程序中,我们通常命名我们创建的线程。例如,我们将创建一个线程并为其命名,例如“WorkerThread”。
Let's say this is part of my log4net config file:
假设这是我的 log4net 配置文件的一部分:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="C:\Logs\MyApp\myapp.log" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="1000MB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c :: %m%n" />
</layout>
</appender>
This configuration will print the following in my log:
此配置将在我的日志中打印以下内容:
2017-03-07 17:00:00,003 [MessagePump Worker] DEBUG MyApp.App :: Blah Blah Blah
I would like it to print:
我希望它打印:
2017-03-07 17:00:00,003 [MessagePump Worker: 2380] DEBUG MyApp.App :: Blah Blah Blah
I am just trying to figure out what I need to put in my Conversion Pattern to also include the ThreadID (2380) as in my example above. I have done some google searches but I can't seem to find a way to print both the "Thread Name" and "Thread ID". Anyone have any ideas?
我只是想弄清楚我需要在我的转换模式中放入什么,以包括上面示例中的 ThreadID (2380)。我已经进行了一些谷歌搜索,但似乎找不到打印“线程名称”和“线程 ID”的方法。谁有想法?
回答by Wouter
In your application thread use:
在您的应用程序线程中使用:
ThreadContext.Properties["threadid"] = Thread.CurrentThread.ManagedThreadId;
in the conversion pattern:
在转换模式中:
%property{threadid}
回答by BobbyA
It may be impossible outside of manually adding a ThreadContext.Property, like in @Wouter's answer.
在手动添加 ThreadContext.Property 之外可能是不可能的,就像@Wouter 的回答一样。
See the documentation here:
请参阅此处的文档:
thread | Used to output the name of the thread that generated the logging event. Uses the thread number if no name is available.
线程| 用于输出生成日志事件的线程的名称。如果没有可用的名称,则使用线程号。
So you only get a thread id if the thread name doesn't exist. I'm frustrated with this myself, as I only want thread ids, even when a thread is named.
因此,如果线程名称不存在,您只会获得一个线程 ID。我自己对此感到沮丧,因为我只想要线程 ID,即使在命名线程时也是如此。

