The following class is probably the world simplest text logger.
There are several ways to open a file and write texts into it but I used File.AppendAllText() method because by using this method, it is guaranteed that the file handle will be closed, even if exceptions are raised.
public static class Logger
{
public static void Log(string message)
{
File.AppendAllText("C:\\MyLogFile.txt", DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ":\t" + message + Environment.NewLine);
}
}
Using the Logger class:
By handling Application.ThreadException event in Program.cs , you can log every un-handled exception into a text file for further examination.
static void Main(string[] args)
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException); //it must be before Application.Run
...
Application.Run();
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Logger.Log(e.Exception.ToString());
}
Tags: AppendAllText, C#, exception, exception logger, exceptionlogger, logfile, logger, ThreadException, tips

Thanks, this tip saves me a lot of trouble.
thanks,.. very nice post
files are exclusively locked in Windows once they are opened by a thread. your so-called logger will raise error if used in multiple threads.