I would like you to review the locking mechanism I implement in C# class. Will it be working correctly with many threads? Please don't mind rest of the code because I just try to repair the class quickly to have a thread safe logging class for my project. Any other suggestions are welcome.
public static class Debug
{
static readonly object _consoleLocker = new object();
static readonly object _diskDriveLocker = new object();
public static void Log(Tryb tryb, int level, string caller, string message, string messageExt)
{
String strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
strAppDir = strAppDir.Replace("file:\\", ""); // dla windowsa
strAppDir = strAppDir.Replace("file:", ""); // dla linuksa
string file = Path.Combine(strAppDir, "log.txt");
ProcessLogMessage(tryb, "[log]", caller, message, messageExt, file);
}
public static void Log(Tryb tryb, int level, string caller, string message, string messageExt, string file)
{
ProcessLogMessage(tryb, "[log]", caller, message, messageExt, file);
}
public static void Error(Tryb tryb, string caller, string message, string messageExt)
{
String strAppDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
strAppDir = strAppDir.Replace("file:\\", ""); // dla windowsa
strAppDir = strAppDir.Replace("file:", ""); // dla linuksa
string file = Path.Combine(strAppDir, "error.txt");
ProcessLogMessage(tryb, "[error]", caller, message, messageExt, file);
}
public static void Error(Tryb tryb, string caller, string message, string messageExt, string file)
{
ProcessLogMessage(tryb, "[error]", caller, message, messageExt, file);
}
static void ProcessLogMessage(Tryb tryb, string rodzaj, string caller, string message, string messageExt, string file)
{
string dane = String.Format("{0}, {1}, {2}, {3}, {4}", DateTime.Now, rodzaj, caller, message, messageExt);
switch (tryb)
{
case Tryb.FILE:
lock (_diskDriveLocker)
{
WriteLogToFile(dane, file);
}
break;
case Tryb.CONSOLE:
lock (_consoleLocker)
{
Console.WriteLine(dane);
}
break;
case Tryb.FILEANDCONSOLE:
lock (_consoleLocker)
{
Console.WriteLine(dane);
}
lock (_diskDriveLocker)
{
WriteLogToFile(dane, file);
}
break;
}
}
static void WriteLogToFile(string strLogMessage, string strLogFile)
{
StreamWriter swLog = null;
try
{
if (!File.Exists(strLogFile))
swLog = new StreamWriter(strLogFile);
else
swLog = File.AppendText(strLogFile);
swLog.WriteLine(strLogMessage);
}
finally
{
if (swLog != null)
{
swLog.Close();
swLog.Dispose();
}
}
}
}
public enum Tryb
{
FILE = 0,
CONSOLE = 1,
FILEANDCONSOLE = 2
}