It’s good practice to log all the error into a file or database so in future you can check, how your application is working, and is there any issue which is not caught by Q.A. team.
Really it's helpful to understand and caught the issues after deploying the application on production server.
Create a method to log the error into a file:
public void LogError(Exception ex, String source)
{
try
{
String LogFile = HttpContext.Current.Request.MapPath("/Errorlog.txt");
if (LogFile != "")
{
String Message = String.Format("{0}{0}=== {1} ==={0}{2}{0}{3}{0}{4}{0}{5}"
, Environment.NewLine
, DateTime.Now
, ex.Message
, source
, ex.InnerException
, ex.StackTrace);
byte[] binLogString = Encoding.Default.GetBytes(Message);
System.IO.FileStream loFile = new System.IO.FileStream(LogFile
, System.IO.FileMode.OpenOrCreate
, System.IO.FileAccess.Write, System.IO.FileShare.Write);
loFile.Seek(0, System.IO.SeekOrigin.End);
loFile.Write(binLogString, 0, binLogString.Length);
loFile.Close();
}
}
catch { /*No need to catch the error here. */}
}
We are using two parameter 1. Exception and 2. String (source where we will pass the page url so we can understand on which page this error occured).
We are loging page URL, Error Message, InnerException and StackTrace. It's enough to understand the reason and page to fix the code.
You can create this method anywhere either in Business Logic Layer or on the Global.asax file itself.
Now open the Global.asax file and in Application_Error method add following lines
void Application_Error(object sender, EventArgs e) {
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
LogError(ex, HttpContext.Current.Request.Path);
Server.ClearError();
}
Add a file on the root with name "Errorlog.txt" and give read and write permission to it so new error can be write in this file, on develpment machine no need to give the read write permission becuase it already have it.
Now your application will log every error in your application to a text file name "Errorlog.txt" on the root of the application.
No comments:
Post a Comment