How to Log an Exception With a Simple Example in C#

Introduction

In this article, I have shared how to log an exception in a text document so that it will be stored permanently in the database. I have attached the source code in the attachment section.

Write the following code in catch block of any event:

  1. protected void btnsave_Click(object sender, EventArgs e)
  2.   {
  3.       try
  4.       {
  5.                     //code requires as per your requirement
  6.       }
  7.       catch(Exception ex)
  8.       {
  9.            //show some appropriate message to the user
  10.           lbldiserr.Text = “Something went wrong in Server, Kindly contact administator”;
  11.            //getting page name also -it is optional
  12.           string senderpagename = Path.GetFileNameWithoutExtension(Page.AppRelativeVirtualPath);
  13.           LogException(ex, senderpagename);
  14.       }
  15.   }
  16. public static void LogException(Exception exc, string senderpagename)
  17.   {
  18.       // Include enterprise logic for logging exceptions 
  19.       // Get the absolute path to the log file 
  20.       string logFile = “~/App_Data/ErrorLog.txt”;
  21.       logFile = HttpContext.Current.Server.MapPath(logFile);
  22.       // Open the log file for append and write the log
  23.       StreamWriter sw = new StreamWriter(logFile, true);
  24.       sw.WriteLine(“********** {0} **********”, DateTime.Now);
  25.       if (exc.InnerException != null)
  26.       {
  27.           sw.Write(“Inner Exception Type: “);
  28.           sw.WriteLine(exc.InnerException.GetType().ToString());
  29.           sw.Write(“Inner Exception: “);
  30.           sw.WriteLine(exc.InnerException.Message);
  31.           sw.Write(“Inner Source: “);
  32.           sw.WriteLine(exc.InnerException.Source);
  33.           if (exc.InnerException.StackTrace != null)
  34.           {
  35.               sw.WriteLine(“Inner Stack Trace: “);
  36.               sw.WriteLine(exc.InnerException.StackTrace);
  37.           }
  38.       }
  39.       sw.Write(“Exception ID:”);
  40.       sw.WriteLine(((System.Data.SqlClient.SqlException)(exc)).Number);
  41.       sw.Write(“Exception Type: “);
  42.       sw.WriteLine(exc.GetType().ToString());
  43.       sw.WriteLine(“Exception: “ + exc.Message);
  44.       sw.WriteLine(“Source: “ + senderpagename);
  45.       sw.WriteLine(“Stack Trace: “);
  46.       if (exc.StackTrace != null)
  47.       {
  48.           sw.WriteLine(exc.StackTrace);
  49.           sw.WriteLine();
  50.       }
  51.       StackTrace stackTrace = new StackTrace();
  52.       StackFrame stackFrame1 = stackTrace.GetFrame(1);
  53.       MethodBase methodBase1 = stackFrame1.GetMethod();
  54.       // Displays “WhatsmyName”
  55.       string Parent_Method_name = methodBase1.Name;
  56.       SqlDatabase objdb = new SqlDatabase(OneStopMethods_Common.constring_Property);
  57.       string  exceptionno = ((System.Data.SqlClient.SqlException)(exc)).Number.ToString();
  58.       string execeptiontype = exc.GetType().ToString();
  59.       string message = exc.Message.Replace(“‘”,“”);
  60.       string sourcepage = senderpagename;
  61.       string whereinsql = ((System.Data.SqlClient.SqlException)(exc)).Procedure;
  62.       string orginalquery = ” insert into adm_app_log(app_log_id,app_log_type,app_log_module_name,app_log_control_name,app_log_routine_name,app_log_desc,date_created,created_by,date_updated,updated_by) “ +
  63.                        “values(Exceptionid,’Exception_Type’,’whichpageoccured’,’whichevent_itoccured’,’Sql_Detail’,’whatismessage’,GETDATE(),’Admin’,GETDATE(),’Admin’)”;
  64.       string replacedquery = orginalquery.Replace(“Exception_Type”, execeptiontype).Replace(“Exceptionid”, exceptionno).Replace(“whatismessage”, message).Replace(“whichevent_itoccured”, Parent_Method_name).Replace(“whichpageoccured”, sourcepage).Replace(“Sql_Detail”, whereinsql);
  65.       objdb.ExecuteDataSet(CommandType.Text, replacedquery);
  66.       //if (EventLog.SourceExists(“karthik_Testing”))
  67.       //{
  68.       //    EventLog eventlog = new EventLog(“TPMS_Log”);
  69.       //    eventlog.Source = “TPMS_Log”;
  70.       //    eventlog.WriteEntry(sw.ToString(), EventLogEntryType.Error);
  71.       //}  
  72.       sw.Close();
  73.   }

I hope the above information was helpful, kindly share your valuable feedback or thoughts.

 

Leave a Reply

Your email address will not be published. Required fields are marked *