Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging in log4net to different appenders based on circumstances

I am using log4net and in one class require logging to a RollingFile appender, but then in another class, I wish to log to the event log + rolling file + console appender.

What is the best practice? and could I see some sample code?

By the way to make things more difficult, I am using Castle Windsor Logging Facility with Log4net to resolve my Logger instance.

If it helps, I was thinking this below, but have no idea if this is best practice, or how to activate a particular logger based on 'name' still utilising my current logger instance from windsor:

log4net.config:

...
    <logger name="EventLogOnly">
      <level value="ALL" />
      <appender-ref ref="EventLogAppender" />
    </logger>
    <logger name="ConsoleEventLog">
      <level value="ALL" />
      <appender-ref ref="ColoredConsoleAppender" />
      <appender-ref ref="EventLogAppender" />
    </logger>
...

castle windsor container builder class:

container.AddFacility("logging.facility", 
   new LoggingFacility(LoggerImplementation.Log4net, "log4net.config"));

class in which to log:

private ILogger Logger;
public Test(ILogger logger) {
  Logger.Info("Can I log under event log only?");
  Logger.Info("Now can I log under both?");
}

Thanks guys.

like image 621
GONeale Avatar asked Nov 05 '09 01:11

GONeale


Video Answer


1 Answers

You can do this by applying a filter to an appender. Only if the log event passes the filter does the event get logged by that appender.

This filter configuration will log only those events coming from the logger named "MyLogger":

<appender name="EventLogAppender" ...
    <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="MyLogger" />
    </filter>       
    <filter type="log4net.Filter.DenyAllFilter" />
</appender>

...and this one will match log messages with certain contained text:

<filter type="log4net.Filter.StringMatchFilter">
    <stringToMatch value="database" />
</filter>
<filter type="log4net.Filter.DenyAllFilter" />

There's a good bit of configuration possible with filters. See the log4net SDK, or the Filters section of the manual, for more details.

like image 128
Michael Petrotta Avatar answered Oct 08 '22 19:10

Michael Petrotta