C# Tips

Simple Exception Logger

Advertisements

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());
}
Advertisements