.Net tools to use: log4net

By | 2010.03.12

log4net

http://logging.apache.org/log4net/

Description
Free popular logging system developed by Apache Foundation.

Difficulty
1 line at top of each class. A standard XML-section in web.config.
Sample usage:

// At the top of every class you set up a static logger with the class name (retrieved through System.Reflection)
private static log4net.ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

// Then in the class you can send data to log files easily
log.DebugFormat("This is not so important.");
log.InfoFormat("Normal log line.");
log.WarningFormat("Should be looked at.");
log.ErrorFormat("Something is wrong.");
log.FatalFormat("Something is horribly wrong. I hope this message is forwarded on e-mail.");

Sample web.config:

<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net debug="false">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender,log4net">
<param name="File" value="MyApplication.log"/>
<param name="AppendToFile" value="true"/>
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/>
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<priority value="ALL"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="TraceAppender"/>
</root>
</log4net>

Advantages

  • Easily configured in web.config to filter what to log.
  • Can write log to text-file, SQL, Trace, ASP.Net Trace, Event Log, SMTP (E-mail), etc.
  • Has several levels based on severity of message; DEBUG, WARNING, ERROR, FATAL, etc
  • Can be set to log only a certain severity level. For example not logging DEBUG in production.
  • Can have multiple destinations. For example write DEBUG to debug.log, ERROR to error.log and send FATAL to e-mail (SMTP).
  • Can be set to filter on class-level or by groups. For example only logging DataAccessLayer-DEBUG messages and ignoring other DEBUG messages.
  • Can be extended with custom modules. For example if you need to look for and react to specific log messages.

Leave a Reply