Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 best way to log request

I want to keep a log of all the requests to my MVC 3 app, including requested URL, user's ip adress, user agent, etc. Where is the best place to do this,

1) use a base controller?

2) use an action filter?

3) others?

like image 372
Laguna Avatar asked Dec 20 '22 16:12

Laguna


2 Answers

I do this inside my BaseController. Something like this:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    // If in Debug mode...
    if (filterContext.HttpContext.IsDebuggingEnabled)
    {
        var message = string.Format(CultureInfo.InvariantCulture,
                                    "Leaving {0}.{1} => {2}",
                                    filterContext.Controller.GetType().Name,
                                    filterContext.ActionDescriptor.ActionName.Trim(),
                                    filterContext.Result);
        Logger.Debug(message);
    }

    // Logs error no matter what
    if (filterContext.Exception != null)
    {
        var message = string.Format(CultureInfo.InvariantCulture,
                                    "Exception occured {0}.{1} => {2}",
                                    filterContext.Controller.GetType().Name,
                                    filterContext.ActionDescriptor.ActionName.Trim(),
                                    filterContext.Exception.Message);
         Logger.Error(message);
     }

     base.OnActionExecuted(filterContext);
}

Hope you get the idea.

You can also log before the action is executed using:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
like image 159
Leniel Maccaferri Avatar answered Dec 31 '22 13:12

Leniel Maccaferri


An HttpModule seems like the best fit, if you ask me.

All of the data you're talking about logging is available well before any particular Controller gets invoked. So if you do logging outside of the controller, then you get to capture even those requests which are not to valid controller actions. And there's no need to clutter your controller code with something that's really a cross-cutting concern.

like image 33
StriplingWarrior Avatar answered Dec 31 '22 14:12

StriplingWarrior