Saturday, January 23, 2016

ErrorLog C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    public static class ErrorLog
    {
        public static void WriteLog(Exception ex, string methodName)
        {
            try
            {
                bool ErrorLoggingRequired = ConfigurationManager.AppSettings["ErrorLoggingRequired"] != null? Convert.ToBoolean(ConfigurationManager.AppSettings["ErrorLoggingRequired"]):true;
                bool ErrorDetailsRequired = ConfigurationManager.AppSettings["ErrorDetailsRequired"] != null ? Convert.ToBoolean(ConfigurationManager.AppSettings["ErrorDetailsRequired"]) : false;

                if (ErrorLoggingRequired)
                {
                    string strMethodName = ex.TargetSite.Name;
                    string strClassName = ((System.Reflection.MemberInfo)(ex.TargetSite)).ReflectedType.Name;
                    string strErrLineNo = ex.StackTrace;
                    StreamWriter srWriterObj = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory.ToString() + @"\Exception.log", true);
                    srWriterObj.NewLine = ("\r\n");
                    srWriterObj.WriteLine(System.DateTime.Now.ToString() + ",--Error: " + ex.Message + ",in method:" + methodName);
                    srWriterObj.NewLine = ("\r\n");
                    if (ErrorDetailsRequired)
                    {
                        srWriterObj.WriteLine("Details: " + strErrLineNo);
                    }
                    //srWriterObj.WriteLine("MethodName: " + strMethodName + " | " + "ClassName: " + strClassName + " | " + "ErrLineNo: " + strErrLineNo);
                    srWriterObj.Flush();
                    srWriterObj.Close();
                }
            }
            catch (Exception ex1)
            {
                string s = ex1.Message;

            }

        }

    }
}

No comments:

Post a Comment