Zaheer's profileZaheer's spaceBlogNetwork Tools Help

Blog


    August 04

    Best logging technique for a Console Application

    Problem:

     

    We had a console application used to exporting data from Database to XML files. There are millions of records in the database therefore this application is likely to take hours to complete its process. As per client and application requirements we need to have a heavy logging throughout the application life cycle to capture time and detail of every event that occurred. Also logging was used to log any exception with details that occurred. The technique currently used had two drawbacks.

     

    • No disable logging facility
      If logging is to be disabled you have to remove every instance from where logging was invoked.
    • File open and close operation on every log entry
      Log file was created at the start of application and then for each log entry the file was opened and closed after the entry was logged, which is consuming a lot CPU time.

     

    Here is the code snippet which was used to log events

     

    public static void DoSomething()

    {

    try

    {

                Logger.WriteLog("DoSomething() - Started processing")

         

    // do something here

     

    Logger.WriteLog("DoSomething() - Done processing")

     

    }

    catch (Exception e)

    {

    Logger.WriteLog("DoSomething() failed : " + e.Message + e.StackTrace);

    }

    }

     

    class Helper

    {

            public static string ErrorLogFile

            {

                get

                {

    return ConfigurationManager.AppSettings["ErrorLogFile"];

                }

            }

    }

     

    class Logger

    {

    public static void WriteLog(string logMsg)

    {

    EnsureLogFileExists(Helper.ErrorLogFile);

    StreamWriter SW;

    SW = File.AppendText(Helper.ErrorLogFile);

    SW.WriteLine("[" + DateTime.Now.ToString() + "] " + logMsg);

    SW.Close();

    }

     

     

    public static void EnsureLogFileExists(string filePath)

    {

    if (!File.Exists(filePath))

    {

    StreamWriter SW;

    SW = File.CreateText(filePath);

    SW.WriteLine("--- Application Starting ---");

    SW.WriteLine("");

    SW.WriteLine("");

    SW.Close();

    }

    }

    }

     

    ========================================================================================================================

     

    Solution:

     

    We used polymorphism with singleton pattern to implement an efficient and robust solution that is much more efficient and effective and also reduces logging time significantly.

     

    Here is the complete code snippet

     

    public static void DoSomething()

    {

        try

        {

            Logger.Start();

            Logger.WriteLog("DoSomething() - Started processing")

            

            // do something here

            Logger.WriteLog("DoSomething() - Done processing")

     

        }

        catch (Exception e)

        {

            Logger.WriteLog("DoSomething() failed : " + e.Message + e.StackTrace);

        }

        finally

        {

            Logger.Close();

        }

    }

     

    class Helper

    {

        public static string ErrorLogFile

        {

            get

            {

                return ConfigurationManager.AppSettings["ErrorLogFile"];

            }

        }

     

        public static bool LoggingEnabled

        {

            get

            {

                return (Convert.ToInt32(
                ConfigurationManager.AppSettings["LoggingEnabled"]) == 1 ? true : false);

            }

        }

     

    }

     

     

    class Logger

    {

        private static LoggingHelper objLoggingHelper;

     

        public static void Start()

        {

            if (Helper.LoggingEnabled)

                objLoggingHelper = new LoggerEnabled();

      else

                objLoggingHelper = new LoggerDisabled();

        }

     

        public static void WriteLog(string logMsg)

        {

            objLoggingHelper.WriteLog(logMsg);

        }

     

        public static void Close()

        {

            objLoggingHelper.Close();

        }

    }

     

    abstract class LoggingHelper

    {

        public abstract void WriteLog(string logMsg);

        public abstract void Close();

    }

     

     

    class LoggerEnabled : LoggingHelper

    {

        private static StreamWriter sw;

     

        public LoggerEnabled()

        {

            // First time - Create file and open for writing

            if (sw == null)

            {

                init();

            }

        }

     

        private static void init()

        {

            try

            {

                if (!File.Exists(Helper.ErrorLogFile))

                {

                    sw = new StreamWriter(Helper.ErrorLogFile, true);

                }

            }

            catch (Exception e)

            {

                throw e;

            }

        }

     

        public override void WriteLog(string logMsg)

        {

            try

            {

                sw.WriteLine("[" + DateTime.Now.ToString() + "] " + logMsg);

            }

            catch (Exception e)

            {

            }

        }

     

        public override void Close()

        {

            try

            {

                if (sw != null)

                {

                    sw.Close();

                }

            }

            catch (Exception e)

            {

            }

        }

    }

     

     

    class LoggerDisabled : LoggingHelper

    {

        public override void WriteLog(string logMsg)

        {

            // Logging disabled - so do nothing

        }

     

        public override void Close()

        {

            // Logging disabled - so do nothing

        }

    }

    Comments (1)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Ahmed Muneebwrote:
    Great work man! :)
    Aug. 13

    Trackbacks

    The trackback URL for this entry is:
    http://zaheertariq.spaces.live.com/blog/cns!44D6CB7FFF33F88!174.trak
    Weblogs that reference this entry
    • None