Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...