Friday, December 10, 2004

One of the essential .Net tools I've found is log4net logging framework. (http://logging.apache.org/log4net/)

I've use it in everything from console apps, windows forms, web forms and dll libraries. A typical use scenario would for a .Net dll library would go like this.

Let's say we have executable named “uniBlogger.Drivers.exe” which is a console application in C#.


1. Create .log4net log file named “uniBlogger.Drivers.exe.log4net' with contents:


 
  
  
  
  
  
  
  
   
  

 

 
  
  
 

2. Add the following code into the “AssemblyInfo.cs” file in the project:

using log4net;

...

// Load the configuration from the 'uniBlogger.Drivers.exe.log4net' file
[assembly: log4net.Config.DOMConfigurator(ConfigFileExtension="log4net", Watch=true)]


3. Create the “log-data” subdirectory, in the directory where the executable resides.


4. For every class you want to participate in logging include the following member handle:

using log4net;

...

// LOG4NET
  private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


5. For every method you want to participate in logging include the following code:

public bool CheckProfileGeneral(){
   
   string sql = "";
   
   MySqlParameter[] p =
   {
    BlogIDParam
   };

   if (LOG.IsInfoEnabled)
   {
    LOG.Info( " class: " + this.GetType().FullName +
     " method: " + System.Reflection.MethodBase.GetCurrentMethod().Name +
     " MySqlParameters: " + LogMySqlParams(p));
   }

...

}


6. That's it! Remember you can make generic calls the the log API via LOG.Error(...), LOG.Warn(...), LOG.Info(...) and LOG.Debug(...) function calls. You get to control which log levels get filtered down via the XML lo4net config file and the log level setting.

posted @ 8:04 PM