ASP.NET MVC: LogError Action Filter

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()



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


public override void OnException(ExceptionContext 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]

About Ruprict

I am a nerd that is a Nerd Wannabe. I have more kids than should be allowed by law, a lovely wife, and a different sense of humor than most. I work in the field of GIS, where I am still trying to find myself on the map. View all posts by Ruprict

6 responses to “ASP.NET MVC: LogError Action Filter

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: