Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
0 like 0 dislike
549 views
in .Net Framework by 32 42 54
I am working on an MVC solutions and I want to create a log exception such as Internal server error as so on, How can I do that in MVC?

1 Answer

1 like 0 dislike
by 32 42 54
 
Best answer

Create a Log Exceptions in MVC

To Log Exceptions in a .NET Application, you should follow the below steps in details:

  1. Create a static class Named LogMiddleware

  2. Create Static Method Named LogError with parameters ( Exception ex , string MethodName )

  3. Invoke this method at any location within your application .

Code:

public static void LogError(Exception ex, string MethodName)
{

    string logPath = ConfigurationManager.AppSettings["LogPath"];
    string filePath = logPath + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
    string ErrorlineNo, Errormsg, extype, exurl, ErrorLocation;

    var line = Environment.NewLine + Environment.NewLine;

    ErrorlineNo = ex.StackTrace.Substring(ex.StackTrace.Length - 7, 7);
    Errormsg = ex.GetType().Name.ToString();
    extype = ex.GetType().ToString();
    exurl = HttpContext.Current.Request.Url.ToString();
    ErrorLocation = ex.Message.ToString();

    try
    {
        logPath = logPath + DateTime.Today.ToString("yyyy-MM-dd") + ".txt";   //Text File Name

        if (!File.Exists(logPath))
        {
            File.Create(logPath).Dispose();
        }
        using (StreamWriter sw = File.AppendText(logPath))
        {
            string error = "Log Written Date:" + " " + DateTime.Now.ToString() + line + 
                           "Error Line No :" + " " + ErrorlineNo + line + 
                           "Error Message:" + " " + Errormsg + line + 
                           "Exception Type:" + " " + extype + line + 
                           "Error Location :" + " " + ErrorLocation + line + 
                           "Error Page Url:" + " " + exurl + line + 
                           "StackTrace:" + " " + ex.StackTrace;

            sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
            sw.WriteLine("-------------------------------------------------------------------------------------");
            sw.WriteLine(line);
            sw.WriteLine(error);
            sw.WriteLine(line);
            sw.WriteLine("MethodName :" + MethodName);
            sw.WriteLine("--------------------------------*End*------------------------------------------");
            sw.WriteLine(line);
            sw.Flush();
            sw.Close();

        }

    }
    catch (Exception e)
    {
        e.ToString();

    }
}

LogPath: Directory on the machine where exception files are deposited.

Result:

Result Log Exception

If you don’t ask, the answer is always NO!
...