ASP.NET MVC: LogError Action Filter

Fri, Oct 31, 2008 2-minute read

I am messing about with the ASP.NET MVC Beta, and have stumbled into the Action Filter arena.  Specifically, I was checking out the HandleError Attribute which redirects to a local or shared error page if an appropriately attributed controller thows an error.  This is similar to the rescue stuff in Rails/MonoRail, and it's nice.

However, we also want to log the error, so I started to put a logger in the Application_Error method of the Global application, but I am not wild about that option.  It either forces me to handle every exception the exact same way or leads me down the path of the Huge Swtich Statement and neither of those paths really blows my skirt up.  If I could just augment the HandleError functionality, which I like, with some configurable logging functionality, which I want, then life would be good.

As you might imagine, this is very easy.  In fact, I bet I haven't even found the easiest way, but I'll write what I did anyway.  Simply subclassing the HandleErrorAttribute class to a new LogErrorAttribute class and overriding OnException does the job.

public class LogErrorAttribute: HandleErrorAttribute

{

private readonly ILog _logger;

public LogErrorAttribute()

{

log4net.Config.BasicConfigurator.Configure();

_logger = log4net.LogManager.GetLogger(GetType());

}

public override void OnException(ExceptionContext filterContext)

{

_logger.Error(filterContext.Exception.Message);

base.OnException(filterContext);

}

}

I am using log4net here, which means I have to put a <log4net> section in my web.config.  It also means that I can change out where/how things are logged using the awesome log4net configuration options.  Very nice.  Also, since I inherit from HandleErrorAttribute, the redirect to the Error views (default and specified) is still in play.  Me likey.  Just attribute your Controller classes and/or methods with [LogError] and the logging just works.

My guess is some of the big brains out there have a better/cleaner way to do this, since I am pretty new to the ASP.NET MVC world.   If so, put it in the comments please.

Reblog this post [with Zemanta]