Chaka
Chaka

Reputation: 1541

Where to catch exception using log4net in a MVC 3 application?

I placed the following code in the global file to catch exception in my mvc application:

 void Application_Error(Object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError().GetBaseException();
            log.Error("Exception", ex);
        }

and the following to trace what controllers are called:

public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (log.IsDebugEnabled)
            {
                var loggingWatch = Stopwatch.StartNew();
                filterContext.HttpContext.Items.Add(StopwatchKey, loggingWatch);

                var message = new StringBuilder();
                message.Append(string.Format("Executing controller: {0}, action: {1}",
                    filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                    filterContext.ActionDescriptor.ActionName));

                log.Debug(message);
            }
        }

Is there more I can do to catch errors involving db, security (like cannot connect to ldap), data issues/casting, etc..?

Upvotes: 0

Views: 569

Answers (1)

jgauffin
jgauffin

Reputation: 101130

The second code snippet could be added to a global action filter (registered in global.asax). The first snippet could be added to a seperate IHttpModule implementation to remove it from global.asax.

Other than that you've added code to the two places where all exceptions will be caught. The first one will be invoked for all non-MVC related exceptions while the later one is for MVC exceptions only (routing excluded)

Upvotes: 1

Related Questions