My application uses several thr开发者_JS百科eads 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.
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>
精彩评论