39
votes

I'm using Log4Net 2.0, I have it working as required but which to add another logger for specific log statements. All logging is done to a single file appender. The change I want to make is that a 3rd party application fires events containing debug/error information, I can catch this information and whilst useful I feel it pollutes the normal application log file, and would instead prefer this to be stored in its own log file.

The end result I would like is a file called log-file.txt with all the logging from the application except the 3rd party logging. And a 2nd file called log-file-3rdparty.txt with logging only from the 3rd party application. The problem I have is setting up Log4Net to have 2 seperate loggers. I have already tried creating a 2nd LogFileAppender and adding it to the root however all this does in puts the same logging statements into both loggers.

Across the application we currently have the GetLogger statement as follows. This ideally needs to stay the same, so existing logging is unchanged. I need a new logger that is not affected by this statement, but is instead instantiated purely for 3rd party logging.

private readonly ILog _log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

And the App.Config as follows.

< log4net>
<logger name="MyApp.Logging">
  <level value="DEBUG"/>
</logger>

<root>
  <level value="ALL" />
  <appender-ref ref="LogFileAppender" />
</root>

<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
  <param name="File" value="log-file.txt" />
  <param name="AppendToFile" value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <param name="Header" value="&#13;&#10;[Application started]&#13;&#10;" />
    <param name="Footer" value="[Application Finished]&#13;&#10;"/>
    <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
  </layout>
</appender>
</ log4net>

Can you help?

EDIT

If it makes any difference. The 3rd party log events are captured in the same class that some of my application log events are also fired from, this is because the class is responsible for controlling the 3rd part software. Is this an issue? I do have some inkling that log4net can differentiate which logger to create based on class names, and if that's the case do i need to refactor the 3rd party logging to its own class?

1

1 Answers

91
votes

You can easily create a special logger like this:

ILog specialLogger = LogManager.GetLogger("SpecialLogger");

You can then configure the system to use a dedicated appender for this logger:

<logger name="SpecialLogger" additivity="false">
   <level value="ALL" />
   <appender-ref ref="SpecialLogFileAppender" />
</logger>
<root>
   <level value="ALL" />
   <appender-ref ref="LogFileAppender" />
</root>