Monday, July 02, 2018

log4net: Why are all logs written to when I invoke just one?

I was trying to get log4net working and I wanted 3 logs:

  • Console
  • Text file
  • Event log
So the config. looked like:
root
      !--level value="ALL" /
      appender-ref ref="ConsoleLog" /
      appender-ref ref="Log" /
      appender-ref ref="EventLog" /--
 /root
and then e.g.:
appender name="ConsoleLog" type="log4net.Appender.ColoredConsoleAppender"
      mapping
        level value="ERROR" /
        foreColor value="White" /
        backColor value="Red, HighIntensity" /
      /mapping
      layout type="log4net.Layout.PatternLayout"
        conversionPattern value="%date [%thread] %level %logger - %message%newline"/
      /layout
/appender 
and called via e.g. :

private static readonly ILog LogConsole = log4net.LogManager.GetLogger("ConsoleLog"); 

But when I tried e.g.

LogConsole.Info

all three logs were invoked and all three entries were written!

Turns out you need to remove the root level and use e.g.:
logger name="ConsoleLog"
      level value="ALL" /
      appender-ref ref="ConsoleLog" /
/logger
where the  "appender-ref" points to the correct log.

Then all works as expected.

Note: angle brackets removed for display purposes!

Enjoy!

No comments: