Amazon Ad

Wednesday, 15 November 2017

Create custom error logs in your ASP.NET application including try/catch errors

Dear All,


Guys I finally managed to catch all the errors coming in the try/catch or outside this block using global.asax file. Below is the code to be done


Create a class named UErrorLog

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace test
{
    public class UException
    {
        public string UserId { get; set; }
        public string ProjectName { get; set; }
        public string PageName { get; set; }
        public string LineNumber { get; set; }
        public string ErrorMessage { get; set; }
        public string ErrorDescription { get; set; }
        public string IpAddress { get; set; }
        public string LogDateTime { get; set; }
        public int? MenuId { get; set; }
    }
    public class ContextInfo
    {
        public Exception ex { get; set; }
        public List<string> Session { get; set; }

    }
   
    public class UErrorLog : Exception
    {
        public UErrorLog()
        {

        }

        public UErrorLog(Exception ex)
        {
            logerror(ex);
        }

        int line = 0;
        string filename = "";

        public void logerror(Exception ex)
        {
            //System.Exception ex = System.Web.HttpContext.Current.Server.GetLastError();
            if (ex != null)
            {
                //This is included in try/catch to handle the case when the database goes down.
                try
                {
                    var stack = new System.Diagnostics.StackTrace(true);
                    //Get the details
                    //System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(ex, true);
                    System.Diagnostics.StackFrame frame =new System.Diagnostics.StackFrame();

                    foreach (System.Diagnostics.StackFrame f in stack.GetFrames())
                    {
                        if (f.GetFileName() != null && f.GetFileLineNumber() > 0)
                        {
                            frame = f;
                        }
                    }

                    if (frame != null)
                    {
                        //if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))
                        //{
                            line = frame.GetFileLineNumber();
                            filename = frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1);

                            if (!filename.Contains("Global.asax"))
                            {

                                UException err = new UException();
                                //Log this error in your database
                                if (System.Web.HttpContext.Current.Session["LoginName"] != null)
                                {
                                    err.UserId = System.Web.HttpContext.Current.Session["LoginName"].ToString();
                                }
                                else
                                {
                                    err.UserId = "";//Session["LoginName"].ToString();
                                }
                                err.ProjectName = "YourProjectName";
                                //err.PageName = this.GetType().BaseType.Name;

                                //Get the page name and line number
                                err.PageName = filename;
                                err.LineNumber = line.ToString();

                                //Error Messages
                                err.ErrorMessage = ex.Message;
                                if (ex.InnerException != null)
                                    err.ErrorDescription = ex.InnerException.ToString() != "" ? ex.InnerException.ToString() : "";
                                else
                                    err.ErrorDescription = "";

                                //Get IP Address
                                string ip = "";
                                ip = GetIPAddress();
                                if (ip == "" || ip == "::1")
                                {
                                    ip = LocalIPAddress();
                                }
                                err.IpAddress = ip;

                                err.LogDateTime = DateTime.Now.ToString("dd MMM yyyy hh:mm tt");

                                string str = "pInsertErrorLog";
                                SqlConnection con = new SqlConnection("data source=.;user id=sa;password=123;database=test");
                                if (con.State == System.Data.ConnectionState.Closed)
                                    con.Open();

                                SqlCommand cmd = new SqlCommand(str, con);
                                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                                cmd.Parameters.AddWithValue("@UserId", err.UserId);
                                cmd.Parameters.AddWithValue("@ProjectName", err.ProjectName);
                                cmd.Parameters.AddWithValue("@PageName", err.PageName);
                                cmd.Parameters.AddWithValue("@LineNumber", err.LineNumber);
                                cmd.Parameters.AddWithValue("@ErrorMessage", err.ErrorMessage);
                                cmd.Parameters.AddWithValue("@ErrorDescription", err.ErrorDescription);
                                cmd.Parameters.AddWithValue("@IpAddress", err.IpAddress);
                                cmd.Parameters.AddWithValue("@LogDateTime", err.LogDateTime);
                                cmd.Parameters.AddWithValue("@MenuId", err.MenuId);
                                cmd.ExecuteNonQuery();
                            }

                        //}//if (line != frame.GetFileLineNumber() && filename != frame.GetFileName().Substring(frame.GetFileName().LastIndexOf("\\") + 1))

                    }//if (frame != null)

                }
                catch (Exception e)
                {

                }
            }
        }

        //For ISP (Internet Service Provider) IP Address
        public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string sIPAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(sIPAddress))
            {
                return context.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                string[] ipArray = sIPAddress.Split(new Char[] { ',' });
                return ipArray[0];
            }
        }


        //For LAN (Local Area Network) IP Address
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

    }
}

In the global.asax file add the following code

protected void Application_Start(object sender, EventArgs e)
        {
            bool _insideFirstChanceExceptionHandler = false;
            AppDomain.CurrentDomain.FirstChanceException += (object source, FirstChanceExceptionEventArgs e1) =>
            {
                if (_insideFirstChanceExceptionHandler)
                {
                    // Prevent recursion if an exception is thrown inside this method
                    return;
                }
                try
                {
                    _insideFirstChanceExceptionHandler = true;
                    new UErrorLog().logerror(e1.Exception);
                    //throw new UErrorLog(e1.Exception);
                }
                catch
                {
                    // You have to catch all exceptions inside this method
                    _insideFirstChanceExceptionHandler = true;
                }
                finally
                {
                    _insideFirstChanceExceptionHandler = false;
                }
                //new UErrorLog().logerror(e1.Exception);
            };

        }


Table is


CREATE TABLE [dbo].[ErrorLog](
    [LogId] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [varchar](50) NULL,
    [ProjectName] [varchar](150) NULL,
    [PageName] [varchar](150) NULL,
    [ErrorMessage] [varchar](max) NULL,
    [ErrorDescription] [varchar](max) NULL,
    [IpAddress] [varchar](20) NULL,
    [LogDateTime] [datetime] NULL,
    [MenuId] [int] NULL,
 CONSTRAINT [PK_ErrorLog] PRIMARY KEY CLUSTERED
(
    [LogId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


-- =============================================
-- Author:        <Ritesh Tandon>
-- Create date: <Create Date,,>
-- Description:    <Record Error Log>
-- =============================================
CREATE PROCEDURE [dbo].[pInsertErrorLog]
    -- Add the parameters for the stored procedure here
    @UserId varchar(50),
    @ProjectName varchar(100),
    @PageName varchar(100),
    @ErrorMessage varchar(max),
    @ErrorDescription varchar(max),
    @IpAddress varchar(20),
    @LogDateTime varchar(150),
    @MenuId int=null
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    INSERT INTO ErrorLog(UserId,ProjectName,PageName,ErrorMessage,ErrorDescription,IpAddress,LogDateTime,MenuId)
    VALUES(@UserId,@ProjectName,@PageName,@ErrorMessage,@ErrorDescription,@IpAddress,@LogDateTime,@MenuId)
END

GO

Another method is to find and replace all catch block with your method name. See the below regular expression which can be easily used in visual studio find and replace with regex option.

Find all catch blocks

catch\s*\(\w*\s*(.*\w)*\)\s*\b*\n*\{

Replace with
$&\n\t\t\tlogerror($1);


Here logerror(); is the method which captures the logs. The method errorlog can be called.

And friends that it, you will get your own logs.

No comments:

Post a Comment

Comments are welcome, Please join me on my Linked In account

http://in.linkedin.com/pub/ritesh-tandon/21/644/33b

How to implement Captcha v3 in ASP.NET

 I was facing an issue of dom parsing in my website. I finally resolved it by using Google Captcha V3. Step 1: Get your keys from https:...