Simple Exception Logger

21 Apr

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());
}
About these ads

4 Responses to “Simple Exception Logger”

  1. Sohail May 15, 2010 at 3:03 pm #

    Thanks, this tip saves me a lot of trouble.

  2. Ecko June 15, 2010 at 1:06 pm #

    thanks,.. very nice post

  3. test September 9, 2011 at 6:17 pm #

    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.

  4. Jochen June 20, 2014 at 5:22 pm #

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: