Logging can be a very useful tool when developing any application. Furthermore, logging is a must when deploying applications to a production environment. Keeping track of errors and informational messages can help you greatly reduce the time it takes to debug and fix a problem. As in any language, there is more than one way to enable logging in .NET. This article will cover getting started with logging using the free log4net framework.
To Get Started
- Get log4net from http://logging.apache.org/log4net/download.html
- Create a sample .NET application that and call it "sampleLoggingApp"
- Create a place to store the log4net DLL, I usually create a "dependencies" directory
- Copy the extracted log4net DLL from "bin\net\2.0\release\log4net.dll" to your "dependencies" directory
- Set your Visual Studio to show all files, include the log4net DLL in your project and add a reference to it in your project
The Fun Stuff
- Create your log4net configuration file, we will call it log4net.config to keep appending to the same file:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="sampleLog.log" />
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
- Set the path to the log4net.config file:
private static String m_log4netConfigFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "log4net.config");
This sets the path of the log4net.config file to be in the same directory are your executable.
- Create a static log instance:
private static readonly ILog m_log = LogManager.GetLogger(typeof(Form1));
Where "Form1" is the name of your application instance.
- Set a build event in Visual Studio that will copy the log4net configuration file in the output directory on every build:
xcopy /y "$(ProjectDir)log4net.config" "$(TargetDir)"
- Write some information to the log:
I have covered the basics of getting started. However, log4net has quite a few more possible configurations such as
- Log to a database table
- Log to the console
- Log to the event log
- Log to an email address
More information for each configuration can be found at http://logging.apache.org/log4net/release/config-examples.html