There are tons of different ways of logging messages / exceptions in .Net/C#. I think that really depends on how the developer team approaches this task. Probably the easiest and most common framework is log4net. I have been asked several times about an example on how to use log4net so I decided to dedicate this post to writing a very simple Logger object. Please note that the discussion about which framework is best / most popular is not part of this entry, however you can find the information in this forum (link here) quite useful.

The code for this logger class is described as follows, I hope you find it useful.


    ///  <summary>
    /// Class to log messages to a file
    /// </summary>

    public static class Logger
        private static ILog log = null;
        private static bool isInitialized = false;

        ///  <summary>
        /// Function to setup a basic Logger
        /// </summary>

        private static void Setup()
            Hierarchy hierarchy = (Hierarchy)LogManager.GetLoggerRepository();

            PatternLayout patternLayout = new PatternLayout();
            patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";

            RollingFileAppender roller = new RollingFileAppender();
            roller.AppendToFile = true;
            roller.File = @"Logs\event.log";
            roller.Layout = patternLayout;
            roller.MaxSizeRollBackups = 5;
            roller.MaximumFileSize = "100MB";
            roller.RollingStyle = RollingFileAppender.RollingMode.Size;
            roller.StaticLogFileName = true;

            MemoryAppender memory = new MemoryAppender();
            hierarchy.Root.Level = Level.Fatal;
            hierarchy.Configured = true;

            log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        ///  <summary>
        /// Function to add entries to log
        /// </summary>

        /// <param name="ex">Exception to log</param>
        public static void Log(Exception ex)
            if (!isInitialized)
                isInitialized = true;
            log.Error(ex.Message, ex);



Please note that this example uses the version which you can get from the Nuget Gallery (link here) using the following command: Install-Package log4net.

Javier Andrés Cáceres Alvis

Microsoft Most Valuable Professional – MVP

Intel Black Belt Software Developer