Domanda

One of my web pages is giving me an:

GET url_plus_query_string_go_here 500 (Internal Server Error)

type of error. How do I set the page/server up so I can log these errors to find out more about them and why they are happening?

È stato utile?

Soluzione

You can use ELMAH to easily log all exceptions.

It adds a message handler to your ASP.NET application that automatically logs your exceptions to a database and provides a web interface to view them.

Aside from setting up the database and adjusting your web.config you don't have to change anything in your application. Especially, you don't have to add try catch handlers to all your controllers.

Altri suggerimenti

You can create a class Log.cs and use write a method to log the exception into a text file. Now call this method in your code (e.g. in catch block). Use following code to create a class log.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TestApp
{
public class Log
{
    protected static string GetFileName()
    {
        return "log.txt";
    }

    public Log()
    {

    }

    public static void Write(string message)
    {
        System.IO.File.AppendAllText(GetFullFilePath(), message + Environment.NewLine);
    }



    public static string ReadAll()
    {
        return System.IO.File.ReadAllText(GetFullFilePath());
    }

    private static string GetFullFilePath()
    {
        return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, GetFileName());
    }
}
}

Now apply following code to insert your exception or anything else which you want to track on run time. I show only catch block here but you can use it anywhere in your code.

    catch (Exception ex)
        {
          Log.Write(DateTime.Now + "  " + ex.Message + "  Something relevant string");
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top