Thread safe C# logging class using the Singleton Pattern


using System.Web;
using System.IO;
using System.Configuration;

namespace Logger
{
	/// <summary>
	/// Summary description for Logger.
	/// </summary>
	public class Logger
	{

		private static System.IO.StreamWriter _Output = null;
		private static Logger _Logger = null;
		private static Object _classLock = typeof(Logger);
		public static string _LogFile = "";
		public static int _LogLevel = 1;

		private Logger()
		{
				
		}

		public static Logger getInstance()
		{
			//lock object to make it thread safe
			lock(_classLock)
			{
				if(_Logger==null)
				{
					_Logger = new Logger();
				
				}	
			}
			return _Logger;
		}

		public static void logError(string s, int severity)
		{
			try
			{
				if(severity <=_LogLevel)
				{
					if (_Output==null)
					{
						_Output = new System.IO.StreamWriter(_LogFile, true, System.Text.UnicodeEncoding.Default);
					}
									
					_Output.WriteLine(System.DateTime.Now + " | " + severity +" | " + s,new object[0]);
									
					if (_Output != null)
					{
						_Output.Close();
						_Output = null;
					}
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message,new object[0]);			
			}
		}

		public static void closeLog()
		{
			try
			{
				if (_Output != null)
				{
					_Output.Close();
					_Output = null;
				}
			}
			catch(Exception ex)
			{
				Console.WriteLine(ex.Message,new object[0]);
			}
		}
	}
}
Advertisements
Posted in C#. Tags: . 1 Comment »

One Response to “Thread safe C# logging class using the Singleton Pattern”

  1. EARNENAMORA Says:

    Hey people of the forum just posting to say that I love the forums a lot and hope everyone keeps posting interesting stuff so I have something to look at every day.

    Also if your searching for a .NET Resources look at the awesome site.


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

%d bloggers like this: