Logger & Singleton Pattern


Problem :

How do you make an instance of an object globally available and guarantee that only one instance of the class is created?

Per MSDN, to ensure that only a single instance of a class can exist, you must control the instantiation process. This implies that you need to prevent other objects from creating an instance of the class by using the instantiation mechanism inherent in the programming language (for example, by using the new operator). The other part of controlling the instantiation is providing a central mechanism by which all objects can obtain a reference to the single instance. (MSDN)

Solution:

Singleton provides a global, single instance by:

  • Making the class create a single instance of itself.
  • Allowing other objects to access this instance through a class method that returns a reference to the instance. A class method is globally accessible.
  • Declaring the class constructor as private so that no other object can create a new instance. ( and this should also make it thread-safe ! )

Let’s take a quick look at the example below,  a simple crisp code is worth 1000 paragraphs, right ? 😉

class LogManager
	{
		private System.IO.FileStream _fs;
		private System.IO.StreamWriter _sw;

		private static LogManager _logger;
		public static LogManager logger
		{
			get
			{

				// this guy ensures singleton instance of LogManager 
				// static instance throughout our application

				if (_logger == null)
					_logger = new LogManager();
				return _logger;
			}
		}
		private LogManager()
		{
			_fs = System.IO.File.OpenWrite(GetExcecutionFolder() + "Application.log");
			_sw = new System.IO.StreamWriter(_fs);
		}

		public void Log(string message)
		{
			StringBuilder formattedMesage = new StringBuilder();
			formattedMesage.AppendLine("Date : " + DateTime.Now.ToString());
			formattedMesage.AppendLine(message);
			_sw.WriteLine(formattedMesage.ToString());
			_sw.Flush();
		}

		private string GetExcecutionFolder()
		{
			return (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\");
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			LogManager.logger.Log("this is how you log throughout your application !");
		}
	}

courtesy

Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s