我希望记录我 MVC 3 应用程序的所有请求日志,包括请求的 URL、用户的 IP 地址和用户代理等。最佳记录位置在哪里?
1)使用基础控制器?
2)使用操作筛选器?
3)其他?
1)使用基础控制器?
2)使用操作筛选器?
3)其他?
您提到的所有日志记录数据都可以在任何特定控制器调用之前获得。因此,如果您在控制器外记录日志,则可以捕获甚至不是有效控制器操作的请求。而且没有必要在控制器代码中添加实际上是横切关注点的内容。
我在我的BaseController中进行这个操作,类似于这样:
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);
}
希望你能理解这个想法。
在执行操作之前,您还可以使用以下方式进行日志记录:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
当渲染单个请求时,您可以触发多个操作方法。在您的布局页面上使用RenderAction进行如下考虑:
Html.RenderAction("Navigation", "Menu")