In ErrorLog we need to keep track of the File and the Function details where this Exception occurs. So, instead of sending the Hardcoded Values (i.e : Function Name , File Name ) to ErrorLog, we can directly get this details from Exception object (i.e : Exception ex) as follows :
Use namespace :
using System.Diagnostics;
using System.Reflection;
using System.Data;
Function where Error Occurred :
/// <summary> /// Get country names /// </summary> public void GetCountryNames() { try { CountryClass Country = new CountryClass(); DataTable dtCountry = new DataTable(); dtCountry = country.GetCountryList(); ddlCountry.DataSource = dtCountry; ddlCountry.DataTextField = "Name"; ddlCountry.DataValueField = "Id"; ddlCountry.DataBind(); ddlCountry.Items.Insert(0. newListItem(_strSelect, "0")); } catch (Exception ex) { //call ErrorLog using the File Details LogError(ex); } finally { country = null; dtCountry = null; } }
ErrorLog Function accepts Exception object as Parameter :
/// <summary> /// Logs the exception. /// </summary> /// <param name="ex"></param> public static void LogError(Exception ex) { // Get the File Details from Exception StackTrace st = new StackTrace(ex); // Get the object of MethodBase from StackTrace MethodBase mb = st.GetFrame(st.FrameCount - 1).GetMethod(); // Get FileName with NameSpace string source = mb.DeclaringType.FullName; // Get Function Name string methodName = mb.Name; //Implement ErrorLog Logics here using the File Details //AddLogError(source, ex, methodName); }