Log4Net Tutorial in C#

0

Category : , ,

Logging Levels

There are seven logging levels, five of which can be called in your code. They are as follows (with the highest being at the top of the list):
  1. OFF - nothing gets logged (cannot be called)
  2. FATAL
  3. ERROR
  4. WARN
  5. INFO
  6. DEBUG
  7. ALL - everything gets logged (cannot be called)

These levels will be used multiple times, both in your code as well as in the config file. There are no set rules on what these levels represent (except the first and last).

Add the following code to the Assembly.cs file.

// Configure log4net using the .config file
 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
 // This will cause log4net to look for a configuration file
 // called TestApp.exe.config in the application base
 // directory (i.e. the directory containing TestApp.exe)
 // The config file will be watched for changes.

Add the following section to the web/app.config file in the node:



    

Create a new section in the web/app.config using log4net as the node name:


 
   
   
   
  
   
 
 
   
   
 
  

Define a static logger variable at the top of your class. Something like this will work:

private static readonly ILog log = LogManager.GetLogger(typeof(Program));

Altogether then, your class might look something like this:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;

namespace log4netDemo
{
  class Program
  {
   // Define a static logger variable so that it references the name of your class
   private static readonly ILog log = LogManager.GetLogger(typeof(Program));

   static void Main(string[] args)
   {
    log.Info("Entering application.");

    for (int i = 0; i < 10; i++)
    {
     log.DebugFormat("Inside of the loop (i = {0})", i);
    }

    log.Info("Exiting application.");
   }
  }
}

my thanks to:
http://www.justinrhinesmith.com/blog/2008/05/12/quick-and-easy-log4net-setup/

0 comments:

Post a Comment