To create an error log file and write the exception details. First of all, what all data needs to be written in the file. Generally we write - date time, exception description, file in which it occured and line number. We define this method in a generic class, say, LogReport.cs and define a static method writeLog (given below). Now whenever an exception occurs we catch it and in catch block call this method as shown:
public void somefunction()
{
try
{
// Do something that throws an exception
}
catch(Exception ex)
{
LogReport.WriteLog(ex); //as WriteLog is a static method no need to create object
}
}
Below given method create a log file in App_data folder with today's date and .log extension. And then it writes the exception message, its source and stack trace into this file.
public static void WriteLog(Exception ex)
{
String LogFilePath = HttpContext.Current.Server.MapPath("~/App_Data");
try
{
if (!Directory.Exists(LogFilePath.ToString() + "/Error_Log"));
{
Directory.CreateDirectory(LogFilePath.ToString() + "/Error_Log");
}
String FileName = System.DateTime.Now.ToString("dd-MM-yyyy");
StreamWriter LogWriter = File.AppendText(LogFilePath.ToString() + "\\Error_Log\\" + FileName.ToString() + ".log");
LogWriter.WriteLine(System.DateTime.Now + " - " + ex.Source.ToString() + " - " + ex.Message.ToString() + " - " + ex.StackTrace.ToString());
LogWriter.Close();
}
catch (Exception egEx)
{
ClsException.WriteLog(egEx);
}
}
public void somefunction()
{
try
{
// Do something that throws an exception
}
catch(Exception ex)
{
LogReport.WriteLog(ex); //as WriteLog is a static method no need to create object
}
}
Below given method create a log file in App_data folder with today's date and .log extension. And then it writes the exception message, its source and stack trace into this file.
public static void WriteLog(Exception ex)
{
String LogFilePath = HttpContext.Current.Server.MapPath("~/App_Data");
try
{
if (!Directory.Exists(LogFilePath.ToString() + "/Error_Log"));
{
Directory.CreateDirectory(LogFilePath.ToString() + "/Error_Log");
}
String FileName = System.DateTime.Now.ToString("dd-MM-yyyy");
StreamWriter LogWriter = File.AppendText(LogFilePath.ToString() + "\\Error_Log\\" + FileName.ToString() + ".log");
LogWriter.WriteLine(System.DateTime.Now + " - " + ex.Source.ToString() + " - " + ex.Message.ToString() + " - " + ex.StackTrace.ToString());
LogWriter.Close();
}
catch (Exception egEx)
{
ClsException.WriteLog(egEx);
}
}
No comments:
Post a Comment