Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Implementing Logging in .Net

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 75
    Comment on it

    For storing errors there are many ways that can be done . Some store it in the database some store it in the TextFile 

     

    So for storing error in the Text File is given here.

     

    First we will create a Logger.cs class into our project which is used to log the error of the application

     

    public sealed class Logger
        {
            private Logger()
            {
            }
    
            private const string logFilePath = "~/Common/LogFile.txt";
    
            private const string InformationStart = "\n" + "\n" + "*******************Information Begin******************";
    
            private const string InformationEnd = "*******************Information End******************" + "\n" + "\n";
    
            private const string ExceptionStart = "\n" + "\n" + "*******************Exception Begin******************";
    
            private const string ExceptionEnd = "***************************Exception End************************" + "\n" + "\n";
            public static void LogInformation(string information)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(logFilePath), true))
                {
                    file.WriteLine(InformationStart);
                    file.WriteLine(String.Format("{0} as on {1} :", "Information log", String.Format("{0:f}", System.DateTime.Now)));
                    file.WriteLine(information);
                    file.WriteLine(InformationEnd);
                }
            }
    
            public static void LogException(Exception exception)
            {
                StringBuilder exceptionDetails = new StringBuilder();
                exceptionDetails.AppendLine(string.Format(CultureInfo.CurrentCulture, "Exception Type:{0}", exception.GetType().Name));
                exceptionDetails.AppendLine(string.Format(CultureInfo.CurrentCulture, "Source:{0}", exception.Source));
                exceptionDetails.AppendLine(string.Format(CultureInfo.CurrentCulture, "Message:{0}", exception.Message));
                exceptionDetails.AppendLine(string.Format(CultureInfo.CurrentCulture, "Stack Tarce:{0}", exception.StackTrace));
    
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(logFilePath), true))
                {
                    file.WriteLine(ExceptionStart);
                    file.WriteLine(String.Format("{0} as on {1} :", "Error log", String.Format("{0:f}", System.DateTime.Now)));
                    file.WriteLine(exceptionDetails.ToString());
                    file.WriteLine(ExceptionEnd);
                }
            }
        }

     

    Here i am creating this log file into the Common folder of my project you can create it anywhere you want

     

    Consuming or using this logger class is very simple

     

     public EmployeeResponse RegisterEmployee(Employee empobj)
            {
                try
                {
                    int result = 0;
                    string accessToken = Guid.NewGuid().ToString();
                    empResponse = new EmployeeResponse();
                    using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
                    {
                        if (sqlConnection.State == ConnectionState.Closed)
                        {
                            sqlConnection.Open();
                        }
                        SqlCommand cmd = new SqlCommand("uspRegisterUser", sqlConnection);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = empobj.FirstName;
                        cmd.Parameters.Add("@LastName", SqlDbType.VarChar, 50).Value = empobj.LastName;
                        cmd.Parameters.Add("@ProfileImage", SqlDbType.VarChar, 500).Value = ConfigurationManager.AppSettings["ProfileImageBaseAddress"].ToString();
                        cmd.Parameters.Add("@JobRoleID", SqlDbType.BigInt).Value = empobj.JobRoleID;
                        cmd.Parameters.Add("@Email", SqlDbType.VarChar, 200).Value = empobj.Email;
                        cmd.Parameters.Add("@CompanyID", SqlDbType.Int).Value = empobj.CompanyId;
                        cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = empobj.Password;
                        cmd.Parameters.Add("@PasswordSalt", SqlDbType.VarChar, 100).Value = Guid.NewGuid().ToString();
                        cmd.Parameters.Add("@AccessToken", SqlDbType.VarChar, 100).Value = accessToken;
                        cmd.Parameters.Add("@DeviceUUID", SqlDbType.VarChar, 50).Value = empobj.DeviceUUID;
                        cmd.Parameters.Add("@DeviceType", SqlDbType.VarChar, 50).Value = empobj.DeviceType;
                        cmd.Parameters.Add("@CreatedDate", SqlDbType.VarChar, 50).Value = System.DateTime.Now;
                        cmd.Parameters.Add("@IsDeleted", SqlDbType.VarChar, 50).Value = empobj.IsDeleted;
                        cmd.Parameters.Add("@DeletedDate", SqlDbType.Date).Value = System.DateTime.Now;
                        result = Convert.ToInt32(cmd.ExecuteNonQuery());
                        switch (result)
                        {
                            case 1:
                                empResponse.Status = true;
                                empResponse.Message = "User successfully registered.";
                                empobj.AccessToken = accessToken;
                                break;
                            case 2:
                                empResponse.Status = false;
                                empResponse.Message = "Email already exists.";
                                break;
                            default:
                                empResponse.Status = false;
                                empResponse.Message = "Registration failed.";
                                break;
                        }
                    }
                }
                catch (SqlException ex)
                {
                    Logger.LogException(ex);
                    empResponse.Status = false;
                    empResponse.Message = ex.Message;
                }
                return empResponse;
            }

     

    So in my API i have used it everywhere you just need to write the class name and its method and inside that pass the exception object it will log it

    .net

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: