logging in log4net to different appenders based on circumstances

折月煮酒 提交于 2019-12-29 06:50:12

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1677877/logging-in-log4net-to-different-appenders-based-on-circumstances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!