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

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

by Karthik Sachin   on Jul 20, 2016   Category: C#  | Level: Beginner  |  Views: 191    |  Points: 100   
Like this article? Bookmark and Share:
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.

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.   
  10.            //show some appropriate message to the user  
  11.           lbldiserr.Text = "Something went wrong in Server, Kindly contact administator";  
  12.   
  13.            //getting page name also -it is optional  
  14.           string senderpagename = Path.GetFileNameWithoutExtension(Page.AppRelativeVirtualPath);  
  15.   
  16.           LogException(ex, senderpagename);  
  17.   
  18.       }  
  19.    
  20.        
  21.   }  
  22.   
  23. public static void LogException(Exception exc, string senderpagename)  
  24.   {  
  25.       // Include enterprise logic for logging exceptions   
  26.       // Get the absolute path to the log file   
  27.       string logFile = "~/App_Data/ErrorLog.txt";  
  28.   
  29.       logFile = HttpContext.Current.Server.MapPath(logFile);  
  30.   
  31.       // Open the log file for append and write the log  
  32.       StreamWriter sw = new StreamWriter(logFile, true);  
  33.       sw.WriteLine("********** {0} **********", DateTime.Now);  
  34.       if (exc.InnerException != null)  
  35.       {  
  36.           sw.Write("Inner Exception Type: ");  
  37.           sw.WriteLine(exc.InnerException.GetType().ToString());  
  38.           sw.Write("Inner Exception: ");  
  39.           sw.WriteLine(exc.InnerException.Message);  
  40.           sw.Write("Inner Source: ");  
  41.           sw.WriteLine(exc.InnerException.Source);  
  42.           if (exc.InnerException.StackTrace != null)  
  43.           {  
  44.               sw.WriteLine("Inner Stack Trace: ");  
  45.               sw.WriteLine(exc.InnerException.StackTrace);  
  46.           }  
  47.       }  
  48.       sw.Write("Exception ID:");  
  49.       sw.WriteLine(((System.Data.SqlClient.SqlException)(exc)).Number);  
  50.       sw.Write("Exception Type: ");  
  51.       sw.WriteLine(exc.GetType().ToString());  
  52.       sw.WriteLine("Exception: " + exc.Message);  
  53.       sw.WriteLine("Source: " + senderpagename);  
  54.       sw.WriteLine("Stack Trace: ");  
  55.       if (exc.StackTrace != null)  
  56.       {  
  57.           sw.WriteLine(exc.StackTrace);  
  58.           sw.WriteLine();  
  59.       }  
  60.      
  61.   
  62.       StackTrace stackTrace = new StackTrace();  
  63.       StackFrame stackFrame1 = stackTrace.GetFrame(1);  
  64.       MethodBase methodBase1 = stackFrame1.GetMethod();  
  65.   
  66.       // Displays “WhatsmyName”  
  67.       string Parent_Method_name = methodBase1.Name;  
  68.   
  69.       SqlDatabase objdb = new SqlDatabase(OneStopMethods_Common.constring_Property);  
  70.       string  exceptionno = ((System.Data.SqlClient.SqlException)(exc)).Number.ToString();  
  71.       string execeptiontype = exc.GetType().ToString();  
  72.       string message = exc.Message.Replace("'","");  
  73.       string sourcepage = senderpagename;  
  74.       string whereinsql = ((System.Data.SqlClient.SqlException)(exc)).Procedure;  
  75.   
  76.       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) " +  
  77.                        "values(Exceptionid,'Exception_Type','whichpageoccured','whichevent_itoccured','Sql_Detail','whatismessage',GETDATE(),'Admin',GETDATE(),'Admin')";  
  78.   
  79.       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);  
  80.                                 
  81.                                 
  82.   
  83.       objdb.ExecuteDataSet(CommandType.Text, replacedquery);  
  84.       //if (EventLog.SourceExists("karthik_Testing"))  
  85.       //{  
  86.       //    EventLog eventlog = new EventLog("TPMS_Log");  
  87.       //    eventlog.Source = "TPMS_Log";  
  88.       //    eventlog.WriteEntry(sw.ToString(), EventLogEntryType.Error);  
  89.       //}    
  90.       sw.Close();  
  91.   }  
I hope the above information was helpful, kindly share your valuable feedback or thoughts.

 



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


No response found, be the first to review this article.

Submit feedback about this article

Please sign in to post feedback

Latest Posts