Home  • Programming • Microsoft .NET Framework

How to make simple Exception Logger in CShare

The following class is probably the world simplest text logger. There are several ways to open a file and write texts into it. You can also use 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() + ":	" + 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());
}

Comments 0


Share

Copyright © 2024. Powered by Intellect Software Ltd