Log4Net Primer

My notes on Log4Net, which is a great logging utility I've been using in a lot of console apps lately. It's beautiful.

References:
Great Introduction Video by Tim Corey - the first 45 minutes were sufficient for me:
Tim Corey’s original article:
Official Documentation, very thorough:


Summary:
log4Net is a great logging tool for .Net applications. You can log at different “levels” like Debug, Info, Warn, Error, Fatal, and send different levels of logging to different places. For example all messages could go to the console, but Error or Fatal messages can go to a log file or a database.


The basic steps are:
  • Add log4Net to your program via NuGet
  • Configure log4Net settings in your App.config
    • Configure various “appenders” for all the targets you want to log to, and what format of message you want each appender to use. You can also filter what “level’ of logging you want each appender to receive.
    • Configure one or more “loggers” and point them to each “appender” as desired. Typically you would just use the “root” logger, but you can add other loggers. Again you can specify “level” filtering at the “logger” level just as you can at the “appender” level.
  • In one place in your program, add the “[assembly: log4net.Config…” line to the top of your main program. (See example below).
  • In each class of your program, add a reference to a “logger”. You can use that logger to log messages.


Below is a barebones sample console app.


App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<log4net>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{ISO8601} [%logger] %level - %message%newline%exception"/>
        </layout>
     <!--Console Appender has no filter so gets all logs.-->
    </appender>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="AppLog.txt" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="5" />
        <maximumFileSize value="1MB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date{ISO8601} [%logger] %level - %message%newline%exception" />
        </layout>
     <!--File Appender gets from INFO logs on up.-->
        <filter type="log4net.Filter.LevelRangeFilter">
            <levelMin value="INFO" />
            <levelMax value="FATAL" />
        </filter>
    </appender>
    <root>
        <level value="ALL"/><!--Logging Level Options: OFF, DEBUG, INFO, WARN, ERROR, FATAL, ALL-->
        <appender-ref ref="ConsoleAppender" />
        <appender-ref ref="RollingFileAppender" />
    </root>
</log4net>
</configuration>


Program.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]//tell log4net to watch the config for changes during runtime
namespace Log4NetTest
{
class Program
{
    private static readonly ILog moLogger = LogManager.GetLogger(typeof(Program));
    static void Main(string[] args)
    {
        Console.WriteLine("Hi.");
        moLogger.Debug("Hey ho, a debug message");
        moLogger.Info("Ho Hey, an info message");
        try
        {
            throw new Exception("Error - Something went wrong!");
       }
        catch(Exception ex)
        {
               moLogger.Error(ex.Message);
        }
        Console.ReadLine();
    }
}
}



Comments

Popular posts from this blog

SQL 2005 SP4 and MSreplication_subscriptions

Hiding an ASPXGridView Delete button with HTMLRowCreated vs. CommandButtonInitialize

SQL Server Deadlocks - Easy Quick Start Guide