Thread safe C# logging class using the Singleton Pattern

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

namespace Logger
{
///

/// Summary description for Logger.
///

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 + ” ” + 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]);
}
}
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *