I have a class (Log) that I use to log all my applications information into a single log file (text file), this class is accessed from many different threads all wanted to write to the same log file using the same Log.Trace(sMessage); static function...
Thing is - and correct me if I am wrong - but the way I am doing it seems extremely prone to contention, errors, and just generally not thread safe...
Currently this is the code I use to peform all my logging operations....
As you can see this is absolutly not threadsafe...
Somehow I have to make this safe enough so that all my threads can use this class to write to the same log file (and I have multiple concurrent running threads...)
Something like CRITICAL SECTIONS or .. arg .. I am totally unsure how to accomplish this ...
And hopefully I can make the change in the Log class and not have to modify the way I acctually call Log.Trace(""); (mind you that is the least of my worries seriously)...
Any ideas, hints, and help would be greatly appreciated, thanks
Thing is - and correct me if I am wrong - but the way I am doing it seems extremely prone to contention, errors, and just generally not thread safe...
Currently this is the code I use to peform all my logging operations....
Code:
public class Log
{
static StreamWriter ErrorLog;
public Log() {}
public static void LogStart(string sFile)
{
// Open Tracer Log File
ErrorLog = new StreamWriter(File.Open(sFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
}
public static void Trace(string sMessage)
{
// Write Trace Log
ErrorLog.WriteLine(sMessage);
ErrorLog.Flush();
}
public void Close()
{
// Close Tracer Log File
ErrorLog.Close();
}
}
As you can see this is absolutly not threadsafe...
Somehow I have to make this safe enough so that all my threads can use this class to write to the same log file (and I have multiple concurrent running threads...)
Something like CRITICAL SECTIONS or .. arg .. I am totally unsure how to accomplish this ...
And hopefully I can make the change in the Log class and not have to modify the way I acctually call Log.Trace(""); (mind you that is the least of my worries seriously)...
Any ideas, hints, and help would be greatly appreciated, thanks