65.9K
CodeProject is changing. Read more.
Home

Create Multiple Sink Files with Log4net

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.62/5 (11 votes)

Jun 13, 2007

CPOL

2 min read

viewsIcon

30300

downloadIcon

309

How to create multiple sink files with Log4net

Introduction

MyLogger library enables you to log the level of errors/events in distinct files. To use MyLogger in your project, add the reference into your project. You will also need to add a reference to Log4net, as MyLogger is nothing but a simple wrapper round Log4net. To start the Logger, place the following code in the start of your application:

Logger.loggerFileName = "LogFile"; 
Logger.StartLoggingThread();

Once the method StartLoggingThread is called, it starts the logger thread. Here in MyLogger, I have included two levels of logging, i.e. Error and Trace, although it can be increased to the same number as provided by Log4net. To log an error, write:

try 
{ 
int i = 10; 
int j = 0; 
int k = i / j; 
} 
catch (Exception ex) 
{ 
Logger.LogMessage("An Error Occurred : " + ex.Message, Logger.LOG_ERROR); 
}

The Logger.LOG_ERROR property lets the MyLogger class know that it is an error and needs to be logged in the error file. Similarly, if you want to trace something, use Logger.LOG_TRACE. For example:

Logger.LogMessage("Reading from File", Logger.LOG_TRACE); 

Remember to ShutDown the logger when you are closing the application. You can write this code in the Application Exit event for your application:

Logger.ShutDownLogger(); 

Details

The above section explains how to use MyLogger in your application. Now I'll explain how MyLogger has been designed and how you can enhance it for further use.

MyLogger runs on a separate thread, thus enabling the application to respond in a comparatively faster fashion and not wait while Log4net logs in the event. This thread becomes active when an event occurs which is notified by the ManualResetEvent.

Currently, there are only two appenders created while MyLogger starts up, but you can modify and add more appenders as per your need. The Logger.LOG_ERROR property lets the MyLogger class know that it is an error and needs to be logged in the error file. The public property loggerFileName is used to set the output filename.