Asp.net MVC Filter监控页面性能和运行时间
本篇文章作用說明:
Asp.net MVC Filter監(jiān)控View實例,監(jiān)控每個View頁面加載的時間,跟蹤分析每個頁面的加載性能,然后做進一步優(yōu)化;
?
問題背景
最近,客戶一直反饋系統(tǒng)使用慢,有時候能夠指出具體是哪個頁面,有時候又只是籠統(tǒng)地反饋慢。這種問題就像是幽靈一樣,
非常不好處理。因為導(dǎo)致這種問題的因素非常之多,而且在開發(fā)工程中,很難模擬出實際運行是的環(huán)境。理論上,對于所有
的頁面做壓力測試是個解決方案,但是這種方式的成本太高,又沒有辦法很快地定位和解決客戶的問題。
最后,考慮通過創(chuàng)建Filter來在訪問Action之前記錄一個時間,在頁面Render完成之后,再記錄一下時間。通過比較這2個時間
的差值來跟蹤每個頁面的加載性能。
?
處理方法
通過過濾器進行跟蹤每個頁面的加載時間,具體通過繼承ActionFilterAttribute, 分別重寫OnActionExecuting和
OnResultExecuted方法進行監(jiān)控和記錄。
?
代碼實例
public class PageLoadPerformanceAttribute : ActionFilterAttribute
{
? ? ? //這里使用log4net來打印出結(jié)果
? ? ? ?private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
? ? ? //創(chuàng)建字典來記錄開始時間,key是訪問的線程Id.
? ? ? ?private readonly Dictionary<int, DateTime> timeMap = new Dictionary<int, DateTime>();
? ? ? //創(chuàng)建字典來記錄當前訪問的頁面Url.
? ? ? ?private readonly Dictionary<int, string > urlMap = new Dictionary<int, string>();
? ? ? ?public override void OnActionExecuting(ActionExecutingContext filterContext)
? ? ? ?{
? ? ? ? ? ?//過濾掉ChildAction, 因為ChildAction實際上不是一個單獨的頁面
? ? ? ? ? ?if(filterContext.IsChildAction) return;
? ? ? ? ? ?var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
? ? ? ? ? ?try
? ? ? ? ? ?{
? ? ? ? ? ? ? ?timeMap.Add(currentThreadId, DateTime.Now);
? ? ? ? ? ? ? ?urlMap.Add(currentThreadId, filterContext.HttpContext.Request.Url == null
? ? ? ? ? ? ? ? ? ?? string.Empty ?: filterContext.HttpContext.Request.Url.AbsoluteUri);
? ? ? ? ? ?}
? ? ? ? ? ?catch (Exception ex)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?Log.Error(ex.ToString());
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?public override void OnResultExecuted(ResultExecutedContext filterContext)
? ? ? ?{
? ? ? ? ? ?var currentThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
? ? ? ? ? ?if (!timeMap.ContainsKey(currentThreadId)) return;
? ? ? ? ? ?try
? ? ? ? ? ?{
? ? ? ? ? ? ? ? //計算出當前頁面訪問耗時
? ? ? ? ? ? ? ?var costSeconds = (DateTime.Now - timeMapt[currentThreadId]).TotalSeconds;
? ? ? ? ? ? ? ?//如果耗時超過2秒,就是用log4net打印出,具體是哪個頁面訪問超過了2秒,具體使用了多長時間。
? ? ? ? ? ? ? ?if (costSeconds > 2)
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?Log.Info(string.Format("Access the action more than 2 seconds. cost seconds {1}. ?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?URL: {0}", urlMap[currentThreadId], costSeconds));
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ? ? ?catch (Exception ex)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?Log.Error(ex.ToString());
? ? ? ? ? ?}
? ? ? ? ? ?finally
? ? ? ? ? ?{
? ? ? ? ? ? ? ?timeMap.Remove(currentThreadId);
? ? ? ? ? ? ? ?urlMap.Remove(currentThreadId);
? ? ? ? ? ?}
? ? ? ?}
? ?}
最后,將該Filter注冊成Global Filter,這樣,就能監(jiān)控系統(tǒng)中所有頁面的加載時間了.
?
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的Asp.net MVC Filter监控页面性能和运行时间的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Asp.net MVC Filter解析
- 下一篇: MQTT.fx连接aliyun阿里云的方