Sunday, November 14, 2010

How to log errors to a Log file everytime an exceptions occurs?

string folder = AppDomain.CurrentDomain.BaseDirectory + GetAppSetting("LogFileDirectory") + "\\";
      CreateDirectory(folder);
      Exception objErr = ex;
      StringBuilder err = new StringBuilder();
      string eol = Environment.NewLine;
      err.Append("Error Time: ").Append(DateTime.Now.Hour).Append(":").Append(DateTime.Now.Minute).Append(eol);
      err.Append("Error Message: ").Append(objErr.Message).Append("\nStack Trace:\n").Append(objErr.StackTrace);
      err.Append("\n**********************************************************************\n");

      if (Convert.ToBoolean(GetAppSetting("SendErrorMail")))
      {
        //Send mail to support when error occured
        string email = GetAppSetting("SupportEmail");
        Email.SendEmail(err.ToString(), email, "", email, "", "Error Message");
      }
      string sErrorTime = DateTime.Now.ToString("dd-MM-yy");

      StreamWriter sw = new StreamWriter(folder + sErrorTime + ".txt", true);
     
      sw.WriteLine(err);
      sw.Flush();
      sw.Close();

No comments:

Post a Comment