Home > Deveploment and Programming > Log error in text file with Tread safe using C#

Log error in text file with Tread safe using C#

Below is the class that is design to log error in the text file asynchronously by multiple threads at a time.

class Logger

{

string _logPath = string.Empty;

const string _fName = “Error.txt”;

string _fileName = string.Empty;

static System.Threading.Semaphore locking = new System.Threading.Semaphore(1, 1);

string fullFileName = string.Empty;

public Logger(string logPath)

{

_logPath = logPath;

}

public Logger(string logPath, string fileName)

{

_logPath = logPath;

_fileName = fileName;

}

public void LogError(string logInformation, EventLogEntryType errorType)

{

if(string.IsNullOrEmpty(logInformation)) return;

if (_fileName.Equals(string.Empty))

fullFileName = _logPath + _fName;

else

fullFileName = _logPath + _fileName;

StringBuilder errorInfo = new StringBuilder();

if (errorInfo.Length > 0) errorInfo.Remove(0, errorInfo.Length);

errorInfo.Append(errorType.ToString() + ” : ” + DateTime.Now.ToString(“dd-MMM-yyyy hh mm ss fff tt”) + ” : “);

errorInfo.Append(” Message – ” + logInformation);

try

{

locking.WaitOne();

StreamWriter Txt = null;

if (File.Exists(fullFileName) == false)

{

Txt = File.CreateText(fullFileName);

}

else

{

Txt = File.AppendText(fullFileName);

FileInfo into = new FileInfo(fullFileName);

long aa = into.Length;

if (aa >= (1024 * 1024))

{

File.Delete(fullFileName);

Txt = File.CreateText(fullFileName);

}

}

Txt.WriteLine(errorInfo.ToString());

Txt.Close();

}

catch (Exception)

{

}

finally

{

locking.Release();

}

}

}

After Creating object of the class, it can be used to log error. Example

Logger log = new Logger(“C:\\”);

log.LogError(“Error occured”, System.Diagnostics.EventLogEntryType.Error);

Advertisements
  1. Red
    30/05/2011 at 1:09 pm

    So whats is the advantage of this code?

    • Gary
      22/07/2011 at 7:52 pm

      Red, the advantage is that you can have multiple threads write entries to the same physical file without them ‘stepping’ on each other. Nice job, Sanjiv!

  2. 02/08/2011 at 3:01 pm

    Goog job sanjiv..

  3. Köpa Viagra
    01/11/2011 at 1:08 am

    Nice idea, please write more

  1. No trackbacks yet.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: