Quantcast
Channel: Rick Schott - _DOT_NET_STUFF and more... » C#
Viewing all articles
Browse latest Browse all 7

Thread safe C# logging class using the Singleton Pattern

$
0
0
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]);
			}
		}
	}
}


Viewing all articles
Browse latest Browse all 7

Trending Articles