我使用此操作过滤器记录执行每个操作所用的时间(可用here):
public class LoggingFilterAttribute : ActionFilterAttribute
{
protected static readonly log4net.ILog log = log4net.LogManager.GetLogger("PerfLog");
private const string StopwatchKey = "DebugLoggingStopWatch";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (log.IsDebugEnabled)
{
var loggingWatch = Stopwatch.StartNew();
filterContext.HttpContext.Items.Add(StopwatchKey, loggingWatch);
log.DebugFormat("Action started: {0}/{1}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName);
}
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (log.IsDebugEnabled)
{
if (filterContext.HttpContext.Items[StopwatchKey] != null)
{
var loggingWatch = (Stopwatch)filterContext.HttpContext.Items[StopwatchKey];
loggingWatch.Stop();
long timeSpent = loggingWatch.ElapsedMilliseconds;
log.DebugFormat("Action started: {0}/{1} - Elapsed: {2}ms",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
filterContext.ActionDescriptor.ActionName,
timeSpent);
filterContext.HttpContext.Items.Remove(StopwatchKey);
}
}
}
}
似乎在解析视图.cshtml文件之前触发了OnActionExecuted。更准确地说,我称之为以下行动:
private IEnumerable<string> GetData()
{
yield return "Item1";
Thread.Sleep(2500);
yield return "Item2";
Thread.Sleep(2500);
yield return "Item3";
}
public ActionResult TestPerf()
{
var model = GetData();
return View(model);
}
虽然页面仅在请求后的5000毫秒内提供,但日志显示:
2014-03-01 20:25:41,630 [12] DEBUG PerfLog - Action started: Test/TestPerf
2014-03-01 20:25:41,632 [12] DEBUG PerfLog - Action finished: Test/TestPerf - Elapsed: 2ms
我不一定对测量网络时间感兴趣(例如,将内容流发送到客户端需要多长时间)。但问题在于,yield-lazy-evaluation可能会隐藏一个缓慢的数据库查询,显然必须通过日志来考虑。
那么,在这种情况下如何在日志中写入5000ms呢?
答案 0 :(得分:3)
我认为您需要OnResultExecuting/ed
而不是OnActionExecuting/ed
。
ActionResult
后执行答案 1 :(得分:0)
actionfilterattribute确实在动作之前执行。您看到的时间是执行过滤器而不是请求。如果你的匹配方法会调用getdata 3次,我会IDD期望5秒。