I just wrote a simple logging class for use among various threads, based on examples I found at MSDN and a few other sites. Problem is, it creates the file log file, but never actually writes anything to it (it writes to the console properly though).
public class Logger
{
private static Logger instance;
private Logger() { }
private static StreamWriter writer;
public static Logger GetInstance()
{
lock (typeof(Logger))
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
}
public void OpenFile(String file)
{
// Open log file for writing and append to it
writer = new StreamWriter(file, true);
}
public void LogMessage(String message)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + message);
Console.WriteLine(dt + message);
}
public void LogError(String error)
{
string dt = DateTime.Now.ToString("yyyy-MM-dd H:mm:ss :: ");
writer.WriteLine(dt + "ERROR: " + error);
Console.WriteLine(dt + "ERROR: " + error);
}
}
and I am doing the following in my Program.
static void Main(string[] args)
{
Logger log = Logger.GetInstance();
log.OpenFile("app.log");
log.LogMessage("Starting App...");
or when you declared the
writerset AutoFlush to true:Edit: Also since your class will access from multi-thread so you should use
lockbefore writing to the stream because theStreamWriterinstance is not thread safe, so: