Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log into separate files per thread with Log4Net?

My application uses several threads with well-defined names (i.e. not a thread pool with 'anonymous' threads). Right now, all of these threads send their log messages to one file - and although the thread ID is part of the log line, this makes it very hard to analyse the application behaviour. Thus, I want each thread to log into its own log file.

It seems that Log4Net offers no built-in option to choose an appender based on the thread. Does anyone know of a solution to this? Note that I obviously would prefer to not switch to another logging library.

like image 908
Jens Bannmann Avatar asked Oct 23 '09 09:10

Jens Bannmann


People also ask

How do I use multiple Appenders in log4net?

You can't log to separate appenders - you need to configure different loggers, and attach the appropriate appender to each one. Then log different messages to the different loggers.

Is log4net asynchronous?

Log4net is a synchronous engine.

Where does log4net log to by default?

In your case, the log file will be in bin\Debug\netcoreapp3. 1\ folder and this may depends on your framework too.


1 Answers

The log4net way of "choosing" appenders is through filtering. In your scenario you would need a way of setting up a number of appenders, each representing a well-defined thread, and have filters in each appender passing through messages only from their respective thread.

Since thread ID is not deterministic you will need something else to do your filtering on. I assume you are controlling the creation of these threads yourself and suggests that each thread registers an identifier in a property in the ThreadContext. Next you can then use the PropertyFilter to filter messages based on the identifiers.

Here's a sample config setup that have two appenders, each appending messages where the current value of property threadId matches a given identifier.

<appender name="x">
    <filter type="log4net.Filter.Property">
        <key value="threadId" />
        <stringToMatch value="threadX" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />
    ...
</appender>

<appender name="y">
    <filter type="log4net.Filter.Property">
        <key value="threadId" />
        <stringToMatch value="threadY" />
    </filter>
    <filter type="log4net.Filter.DenyAllFilter" />
    ...
</appender>

<root>
    <appender-ref name="x" />
    <appender-ref name="y" />
</root>
like image 174
Peter Lillevold Avatar answered Oct 02 '22 11:10

Peter Lillevold