Thread implementação de classe de log seguro
A seguir, seria a maneira correta de implementar uma classe de log segura e segura para thread
Sei que nunca fecho explicitamente oTextWriter
, Aquilo seria um problema
Quando inicialmente usei oTextWriter.Synchronized
, ele não pareceu funcionar até eu inicializá-lo em um construtor estático e torná-lo somente da seguinte maneira:
public static class Logger
{
static readonly TextWriter tw;
static Logger()
{
tw = TextWriter.Synchronized(File.AppendText(SPath() + "\\Log.txt"));
}
public static string SPath()
{
return ConfigManager.GetAppSetting("logPath");
}
public static void Write(string logMessage)
{
try
{
Log(logMessage, tw);
}
catch (IOException e)
{
tw.Close();
}
}
public static void Log(string logMessage, TextWriter w)
{
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine("-------------------------------");
// Update the underlying file.
w.Flush();
}
}