Log4Net- A Closer Look
Log4net is an open source event logging and tracing framework from the Apache Software Foundation. It is the .Net version of the Java open source project- log4j.
List of Appenders
Introduction
We all know about the importance of logging events, exceptions or other important
operation done through our application. When we are about to debug an application,
the logs help us a lot and inform us where to start with. It shows the state of
the application at any given point. This is the reason why we need a logging service
included in our solution set. I am introducing one such logging service- a ready
to implement framework- which I found it very useful called Log4net.
About Log4Net
Log4net is an open source event logging and tracing framework from the Apache Software
Foundation. It emerged as a port to the well known Apache Java project called log4j.
Log4Net is initially created by NeoWorks as a branch from Log4j, released on September
2001 and later donated to Apache on December 2003. Now it became an Apache sponsored
initiative within the "Apache Logging Services" group of projects. Similar projects
are Log4cxx, Log4j, Log4Perl, Log4PHP, and Log4PLSQL. AS the names suggests they
are available for the corresponding technologies.
Features of Log4Net.
Fast and flexible Hierarchical, named logging categories Multiple logging levels
Output to multiple logging targets Dynamic XML Configuration Thread Safe Format
of logs is easily changed Proven architecture (log4j) Modular and extensible design
Support for multiple frameworks
License As Provided by Apache.
Log4Net uses Apache's open source license: Apache License 2.0. It is a free to use,
modify and distributable license and also allows enterprises to use with commercial
softwares. Apaches only requires that a notice informing recipients that Apache
licensed code has been used. Two files must be put in the top directory of the software:
A Quick Example
in the log4net distribution.
class Program
{
static void Main( string[] args )
{
log4net.Config.BasicConfigurator.Configure();
log4net.ILog logger = log4net.LogManager.GetLogger( typeof( Program ) );
logger.Debug("Debug Example" );
logger.Info( "Info Example" );
logger.Warn( "Warning Example");
logger.Error( "Error Example" );
logger.Fatal( "Fatal Example" );
Console.ReadLine();
} }
The Structure of log4net
Log4net is built using the layered approach, with five main components inside of
the framework.
Logger
Logger is the main component with which your application interacts. It is the basic
component that generates the log messages. Logger provides different methods to
log any message. The framework defines an interface called ILog which can be implemented
to create custom loggers of you own.
public interface ILog
{
void Debug(object message);
void Info(object message);
void Warn(object message);
void Error(object message);
void Fatal(ob /* There are overloads for all of the above methods which supports
exceptions. Each overload in that case takes an addition parameter of type Exception
like the one below.*/
void Debug(object message, Exception ex);
/* The Boolean properties are used to check the Logger's level (as we'll see Logging
Levels in the next section) */
bool isDebugEnabled;
bool isInfoEnabled;
// other boolean properties for each method }
Logging Levels
Appender
Appender is an object that persists your log messages someplace. Different
Appenders are available in the framework that relays the output to different
output streams. For e.g. log4net.Appender.ConsoleAppender appends logging events to the console. Framework contains almost all appenders you will need Easy to write your own Multiple appenders can be attached to each logger Each appender can receive logs from multiple loggers
AdoNetAppender
Appender that logs to a database.AnsiColorTerminalAppender
Appends logging events to the terminal using ANSI color escape sequences.AspNetTraceAppender
Appends log events to the ASP.NET TraceContext system.BufferingForwardingAppender
Buffers events and then forwards them to attached appenders.ColoredConsoleAppender
Appends logging events to the console.ConsoleAppender
Appends logging events to the console.DebugAppender
Appends log events to the Debug system.EventLogAppender
Writes events to the system event log.ForwardingAppender
This appender forwards logging events to attached appenders.FileAppender
Appends logging events to a file.LocalSyslogAppender
Logs events to a local syslog service.MemoryAppender
Stores logging events in an array.NetSendAppender
Logs entries by sending network messages using the NetMessageBufferSend native function.OutputDebugStringAppender
Appends log events to the OutputDebugString system.RemoteSyslogAppender
Appends log events to the OutputDebugString system.RemotingAppender
Logs events to a remote syslog daemon.RollingFileAppender
Delivers logging events to a remote logging sink.SmtpAppender
Send an e-mail when a specific logging event occurs, typically on errors or fatal
errors.SmtpPickupDirAppender
Rather than sending via smtp it writes a file that another service, such as
the IIS SMTP agent, can use to manage sending the messages.TelnetAppender
Appender that allows clients to connect via Telnet to receive log messages.TraceAppender
Appends log events to the Trace system.UdpAppender
Sends logging events as connectionless UDP datagrams to a remote host or multicast
using the UdpClient class.
Layout
The Layout component is used to display the final formatted output to the user.
Output can be shown in multiple formats, depending upon the layout. Layout can be
linear or an XML file. Works with an appender. There is a list of different layouts
in the API documentation. You cannot use Multiple layouts cannot be used with an
appender. Inherit the log4net.Layout.LayoutSkeleton class, which implements the
ILayout interface to create your own layout. Commonly used layout is "Patternlayout".
Object Renderers
Log4net renders objects using their ToString() method If you want more control over
that, you can create and use your own renderer Derive from IObjectRenderer interface
Repository
Repository is the layer responsible for maintaining the organization of loggers
Implement a repository using the log4net.Repository.ILoggerRepository interface.
LogManager class can be used to automatically manage the repositories and the loggers.
Sample Application
Sample application that logs to a text file.
- Getting Started
- Add a reference to log4net
- Add an XmlConfigurator attribute to your assembly
- Add an application configuration file
- Add a log4net using statement
- Get a static ILogmember for your class using LogManager.GetLogger()
- Use the static ILogmember to log
Configuration
Log4net uses Fully configurable programmatically easier and more flexible to use
XML configuration files. There are several ways to specify configuration file Application config
file ( AssemblyName.config or web.config ): XmlConfiguratorAttribute on the assembly
XmlConfigurator.Configure( filename )
Why Log4Net
- Open Source Works on all versions of .NET.
- The much improved logging of EntLib 2.0 and above is only available if your application
is running on .NET 2.0 or greater. - Simpler install
- When using the Enterprise Library there are some services you really should install.
This is as simple as running a bat file included with EntLib but it does complicate
your deployment process.
- When using the Enterprise Library there are some services you really should install.
- Faster than its alternatives Appender Buffering -
- Buffering support with some appenders lets log4net queue up log entries and write
them in a single go. If you are writing entries to the database then buffering is
a good way to improve performance.
- Buffering support with some appenders lets log4net queue up log entries and write
- More platforms - Enterprise Library does not support the .NET Compact Framework
while log4net does.
Alternatives
- Enterprise Library 3.1 Logging Application Block
TheEnterprise Library 3.1 Logging Application Block from Microsoft Patterns & Practices
is possibly a good choice if you are already using Enterprise Library. It is a bit
heavy-weight Logging requires more code. Learn more from:
http://msdn2.microsoft.com/en-us/aa480464.aspx. - NLog
NLog API is similar to log4net Easy to configure BSD License .NET, C/C++ and COM
interfaces Project hasn't been updated since its 1.0 release in Sept 2006 .
- NET Logging Framework
This is a lightweight but not as flexible as log4net. It has got a very little community
support and more error prone. Moreover,it can also affect the overall performance
Best Practices
- Logging is only useful if you use it
- Two styles of logging
- Logging by software component
- Logging by functional area
- Log all exceptions, not just their message strings
- Use the format logging methods where appropriate
- Short circuit expensive logging with the various Is…Enabled properties
- Advice on Log Levels
- FATAL - For very serious errors that may crash the program
- ERROR - For errors that may corrupt data or cause improper program behaviour
- WARN - For errors that have been handled but that developers may want to track
- INFO - Non-verbose logging of program execution like startup of sub-systems, timings,
remoting calls, etc.
- DEBUG – For verbose or low level debugging information mainly used to help the developer
debug the system can be used in loops, for dumping data, detailed program flow,
etc.
- FATAL - For very serious errors that may crash the program
- ERROR - For errors that may corrupt data or cause improper program behaviour
- WARN - For errors that have been handled but that developers may want to track
- INFO - Non-verbose logging of program execution like startup of sub-systems, timings,
remoting calls, etc. - DEBUG – For verbose or low level debugging information mainly used to help the developer
debug the system can be used in loops, for dumping data, detailed program flow,
etc.
