Laguna
Laguna

Reputation: 3866

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?

Upvotes: 4

Views: 4162

Answers (3)

Fosna
Fosna

Reputation: 2150

You can have multiple action methods triggered when rendering a single request. Consider using RenderAction on your layout page as follows:

Html.RenderAction("Navigation", "Menu")

It's worth noting that you'd then have two log entries with the same information if you choose to use action filter for logging.

Upvotes: -1

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102378

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)

Upvotes: 6

StriplingWarrior
StriplingWarrior

Reputation: 156459

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.

Upvotes: 6

Related Questions