.Net tools to use: log4net

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:

[sourcecode language=”csharp”]
// 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.”);
[/sourcecode]

Sample web.config:

[sourcecode language=”xml”]
<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>
[/sourcecode]

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: