How to enter separate files on a stream using Log4Net?

My application uses several threads with well-defined names (ie not a thread pool with "anonymous" threads). Right now, all these threads are sending their log messages to a single file - and although the thread ID is part of the log line, this makes it difficult to analyze the behavior of the application. Thus, I want each thread to register in its own log file.

Log4Net does not seem to have a built-in option for selecting a stream-based application. Does anyone know of a solution to this? Note that I obviously would prefer not to switch to another logging library.

+5
source share
1 answer

The log4net way to “select” applications is filtering. In your scenario, you will need a way to create several add-ons, each of which represents a well-defined stream, as well as filters in each application that go through messages only from the corresponding stream.

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

, , , threadId .

<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>
+3

All Articles