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()); }
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.
Yes, “test” is right. When in a multi-threaded environment, the best way to avoid the log file being blocked is to delegate writing to the file to a single background-task (thread). Log entries are transferred to the background-thread using a queue. See here:
http://www.codeproject.com/Tips/585796/Simple-Log
How this can be done thread-safe in a single class.