Monday, January 30, 2012

Best Extension Methods: Log Exception

One of the best extension method to log / email the exception of the application.
//log exception  like: try
    //{
    //    //Your stuff here
    //}
    //catch(Exception ex)
    //{
    //    ex.Log();
    //}
    public static void Log(this Exception ex, string additionalMessage = "")
    {
        StringBuilder msg = new StringBuilder();

        if (!string.IsNullOrEmpty(additionalMessage))
        {
            msg.Append(additionalMessage);
            msg.Append(Environment.NewLine);
        }

        if (ex != null)
        {
            try
            {
                Exception orgEx = ex;

                msg.Append("Exception:");
                msg.Append(Environment.NewLine);
                while (orgEx != null)
                {
                    msg.Append(orgEx.Message);
                    msg.Append(Environment.NewLine);
                    orgEx = orgEx.InnerException;
                }

                if (ex.Data != null)
                {
                    foreach (object i in ex.Data)
                    {
                        msg.Append("Data :");
                        msg.Append(i.ToString());
                        msg.Append(Environment.NewLine);
                    }
                }

                if (ex.StackTrace != null)
                {
                    msg.Append("StackTrace:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.StackTrace.ToString());
                    msg.Append(Environment.NewLine);
                }

                if (ex.Source != null)
                {
                    msg.Append("Source:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.Source);
                    msg.Append(Environment.NewLine);
                }

                if (ex.TargetSite != null)
                {
                    msg.Append("TargetSite:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.TargetSite.ToString());
                    msg.Append(Environment.NewLine);
                }

                Exception baseException = ex.GetBaseException();
                if (baseException != null)
                {
                    msg.Append("BaseException:");
                    msg.Append(Environment.NewLine);
                    msg.Append(ex.GetBaseException());
                }
            }
            finally
            {
            }
        }
        // log this or email to admin return msg.ToString();
    }

Compiled BY: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates