Click here to Skip to main content
11,637,002 members (67,563 online)
Click here to Skip to main content
Add your own
alternative version

A C# Central Logging Mechanism using the Observer and Singleton Patterns

, 18 Feb 2008 CPOL 70.9K 720 76
A very powerful and clean way to add logging of all sorts to an application
using System;
using System.Collections.Generic;
using System.Text;

namespace LoggingSample
{
    class Logger
    {
        #region Data
        private static object mLock = new object();

        private static Logger mLogger = null;

        public static Logger Instance
        {
            get 
            {
                // If this is the first time we�re referring to the
                // singleton object, the private variable will be null.
                if (mLogger == null)
                {
                    // for thread safety, lock an object when
                    // instantiating the new Logger object. This prevents
                    // other threads from performing the same block at the
                    // same time.
                    lock (mLock)
                    {
                        // Two or more threads might have found a null
                        // mLogger and are therefore trying to create a 
                        // new one. One thread will get to lock first, and
                        // the other one will wait until mLock is released.
                        // Once the second thread can get through, mLogger
                        // will have already been instantiated by the first
                        // thread so test the variable again. 
                        if (mLogger == null)
                        {
                            mLogger = new Logger();
                        }
                    }
                }
                return mLogger;
            }
        }

        private List<ILogger> mObservers;

        #endregion

        #region Constructor
        private Logger()
        {
            mObservers = new List<ILogger>();
        }
        #endregion

        #region Public methods
        public void RegisterObserver(ILogger observer)
        {
            if (!mObservers.Contains(observer))
            {
                mObservers.Add (observer);
            }
        }

        public void AddLogMessage(string message)
        {
            // Apply some basic formatting like the current timestamp
            string formattedMessage = string.Format("{0} - {1}", DateTime.Now.ToString(), message);
            foreach (ILogger observer in mObservers)
            {
                observer.ProcessLogMessage(formattedMessage);
            }
        }

        public void AddLogMessage(Exception ex)
        {
            StringBuilder message = new StringBuilder(ex.Message);
            string trace = ex.StackTrace;

            while (ex.InnerException != null)
            {
                ex = ex.InnerException;
                message.Append("\n" + ex.Message);
            }
            message.Append("\nStack trace: " + trace);

            AddLogMessage(message.ToString());
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

David Catriel
Team Leader
Canada Canada
A developer that's been tinkering with computers since he first laid eyes on his buddy's Atari in the mid 80's and messed around with GWBasic and Logo. He now divides his time among his wife, kids, and evil mistress (a term lovingly [ahem...] given to his computer by the wife ...).

For more info, please see my LinkedIn profile: http://www.linkedin.com/pub/david-catriel/44/b01/382

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 18 Feb 2008
Article Copyright 2007 by David Catriel
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid