Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging errors in ASP.NET MVC

I'm currently using log4net in my ASP.NET MVC application to log exceptions. The way I'm doing this is by having all my controllers inherit from a BaseController class. In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:

protected override void OnActionExecuted(ActionExecutedContext filterContext) {     // Log any exceptions     ILog log = LogManager.GetLogger(filterContext.Controller.GetType());      if (filterContext.Exception != null)     {         log.Error("Unhandled exception: " + filterContext.Exception.Message +             ". Stack trace: " + filterContext.Exception.StackTrace,              filterContext.Exception);     } } 

This works great if an unhandled exception occurred during a controller action.

As for 404 errors, I have a custom error set up in my web.config like so:

<customErrors mode="On">     <error statusCode="404" redirect="~/page-not-found"/> </customErrors> 

And in the controller action that handles the "page-not-found" url, I log the original url being requested:

[AcceptVerbs(HttpVerbs.Get)] public ActionResult PageNotFound() {     log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));      return View(); } 

And this also works.

The problem that I'm having is how to log errors that are on the .aspx pages themselves. Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:

<% ThisIsNotAValidFunction(); %> <% throw new Exception("help!"); %> 

It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method. I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.

like image 819
Kevin Pang Avatar asked Feb 20 '09 11:02

Kevin Pang


People also ask

What is logging in ASP.NET MVC?

ASP.NET MVC loggingLogging frameworks typically support multiple "sinks" (or targets or appenders) for log output, such as text files, databases, or even emails. They use configuration to determine which levels of log messages from which parts of the system are routed to different sinks.

What is error logging in asp net?

ELMAH (Error Logging Modules and Handlers) is an error logging facility that you plug into your ASP.NET application as a NuGet package. ELMAH provides the following capabilities: Logging of unhandled exceptions. A web page to view the entire log of recoded unhandled exceptions.

What is used to handle an error in MVC?

ASP.NET MVC has HandleError Attribute (Action Filter), which provides one of the simplest ways to handle errors.


2 Answers

I would consider simplifying your web application by plugging in Elmah.

You add the Elmah assembly to your project and then configure your web.config. It will then log exceptions created at controller or page level. It can be configured to log to various different places (like SQL Server, Email etc). It also provides a web frontend, so that you can browse through the log of exceptions.

Its the first thing I add to any asp.net mvc app I create.

I still use log4net, but I tend to use it for logging debug/info, and leave all exceptions to Elmah.

You can also find more information in the question How do you log errors (Exceptions) in your ASP.NET apps?.

like image 146
Andrew Rimmer Avatar answered Oct 15 '22 15:10

Andrew Rimmer


You can hook into the OnError event in the Global.asax.

Something like this:

/// <summary> /// Handles the Error event of the Application control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void Application_Error(object sender, EventArgs e) {     if (Server != null)     {         Exception ex = Server.GetLastError();          if (Response.StatusCode != 404 )         {             Logging.Error("Caught in Global.asax", ex);         }      }   } 
like image 29
Chuck Conway Avatar answered Oct 15 '22 16:10

Chuck Conway