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.
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.
Log4net is a synchronous engine.
In your case, the log file will be in bin\Debug\netcoreapp3. 1\ folder and this may depends on your framework too.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With