I'm curious what people think about this little bit of logging code. It seems to work ok. Is there anything I'm missing?
public static class Logger
{
private static readonly object Locker = new object();
private static readonly StreamWriter Writer =
new StreamWriter("c:\\temp\\logtester.log", true) ;
public static void Log(string message)
{
Action<string> action = MessageWriter;
action.BeginInvoke(message, null, null);
}
private static void MessageWriter(string message)
{
lock(Locker)
{
Writer.WriteLine(message);
}
}
}
Using Jesse's code, but with QueueUserWorkItem
instead of BeginInvoke
.
public sealed class Logger : IDisposable
{
private static readonly object Locker = new object();
private static readonly StreamWriter Writer = new StreamWriter("c:\\temp\\logtester.log", true);
private static bool _disposed;
public static void Log(string message)
{
ThreadPool.QueueUserWorkItem(MessageWriter, message);
}
private static void MessageWriter(object message)
{
if (!(message is string)) return;
lock (Locker)
{
Writer.WriteLine(message);
}
}
~Logger()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
lock (Locker)
{
if (_disposed)
return;
if (disposing)
{
if (Writer != null)
Writer.Dispose();
}
_disposed = true;
}
}
}