Search code examples
c#.netvb.netlog4net

Log4Net printing "ThreadID" and "Thread Name" in the log


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".

Let's say this is part of my log4net config file:

 <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?


Solution

  • In your application thread use:

    ThreadContext.Properties["threadid"] = Thread.CurrentThread.ManagedThreadId;
    

    in the conversion pattern:

    %property{threadid}