C#.Net Mvc运营监控,计算方法/接口/action/页面执行时间
标签:
1、建立一个TimingActionFilter过滤器
public
class
TimingActionFilter : ActionFilterAttribute
{
public
override
void
OnActionExecuting(ActionExecutingContext filterContext)
{
GetTimer(filterContext,
"action"
).Start();
base
.OnActionExecuting(filterContext);
}
public
override
void
OnActionExecuted(ActionExecutedContext filterContext)
{
GetTimer(filterContext,
"action"
).Stop();
base
.OnActionExecuted(filterContext);
}
public
override
void
OnResultExecuted(ResultExecutedContext filterContext)
{
var
renderTimer = GetTimer(filterContext,
"render"
);
renderTimer.Stop();
var
actionTimer = GetTimer(filterContext,
"action"
);
if
(actionTimer.ElapsedMilliseconds >= 100 || renderTimer.ElapsedMilliseconds >= 100)
{
LogHelper.WriteLog(
"运营监控("
+ filterContext.RouteData.Values[
"controller"
] +
")"
, String.Format(
"【{0}】-【{1}】,执行:{2}ms,渲染:{3}ms"
,
filterContext.RouteData.Values[
"controller"
],
filterContext.RouteData.Values[
"action"
],
actionTimer.ElapsedMilliseconds,
renderTimer.ElapsedMilliseconds
));
}
base
.OnResultExecuted(filterContext);
}
public
override
void
OnResultExecuting(ResultExecutingContext filterContext)
{
GetTimer(filterContext,
"render"
).Start();
base
.OnResultExecuting(filterContext);
}
private
Stopwatch GetTimer(ControllerContext context,
string
name)
{
string
key =
"__timer__"
+ name;
if
(context.HttpContext.Items.Contains(key))
{
return
(Stopwatch)context.HttpContext.Items[key];
}
var
result =
new
Stopwatch();
context.HttpContext.Items[key] = result;
return
result;
}
}
|
其中LogHelper.WriteLog是我的写日志文件通用类,修改成你自己的即可。
3、给controller或action加上特性
4、执行时间或渲染时间大于100ms会被记录下来
我这里有好几次执行时间7、800ms是因为每次重新生成项目,所以第一次会这么慢,这种不管它就是了:)
本文来自:http://www.itdos.com/Mvc/20150324/0126300.html