user350543
user350543

Reputation: 1

Logging exception without changing existing code

I have a application, and I want to log exceptions to a file and I don't want to change any code. I just want a component to which I can add my code and it will start logging exceptions. How can I do this?

Upvotes: 0

Views: 78

Answers (3)

Jakob Gade
Jakob Gade

Reputation: 12419

ASP.NET Health Monitoring is pretty useful, you just need to configure it in web.config.

Upvotes: 0

Randy Levy
Randy Levy

Reputation: 22655

ELMAH (Error Logging Modules and Handlers)

is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74899

In ASP.NET you can create a custom IHttpModule implementation and in it's Init method register an event handler for HttpApplication.Error. Log exceptions as needed when the error event is triggered.

using System;
using System.Web;

namespace ConsoleApplication1
{
    public class ErrorLoggingModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.Error += OnError;
        }

        private static void OnError(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            // log exception here...
        }

        public void Dispose()
        {           
        }
    }
}

Upvotes: 2

Related Questions