Tuesday, October 7, 2008

Common Method to Log Exception - C#


As per friend's request i am posting the code for a common method to log the exceptions which may occur in you application;
We can place this code in one of your common classes and call this method from the Catch block passing the exception object as its parameter.

Following is the code;

public void logException(Exception ex)


string strMethodName = ex.TargetSite.Name;

string strClassName = ((System.Reflection.MemberInfo)(ex.TargetSite)).ReflectedType.Name;

string strErrLineNo = ex.StackTrace;

StreamWriter srWriterObj = new StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath +@"\Zlog\Exception.log", true);

srWriterObj.NewLine = ("\r\n");

srWriterObj.WriteLine ("Error: " + ex.Message + " on " + System.DateTime.Now.ToString());

srWriterObj.NewLine = ("\r\n");

srWriterObj.WriteLine("MethodName: " + strMethodName + " | " + "ClassName: " + strClassName + " | " + "ErrLineNo: " + strErrLineNo);




Just create the object of the class and call your exception method as shown below to log exceptions;

catch (Exception ex)


GServices objGServices = new GServices();



Note: Additional Namespace to be added for the above code are System.Reflection and System.IO

Mohammed Fauzi ~ 4Z


Anonymous said...

excellent boss... short and sweet

Anonymous said...

one should note that this is only safe for single threaded applications and the file should be locked in a multithreaded app.