asp.net 简单记录请求的客户端和服务端 处理时间

最近项目需要简单记录一下 ajax客户端和服务端处理时间,服务端时间的思路是借用BeginRequest和EndRequest事件,为了不影响现有接口返回的数据格式,因此服务处理时间放在response 的header里面。

  BeginRequest += (sender, args) => {
               HttpContext.Current.Items["ServerStartTime"] = DateTime.Now.Ticks.ToString();
            };
            EndRequest += (sender, args) => {
                long ticks = ConvertUtil.ToLong(HttpContext.Current.Items["ServerStartTime"], 0);
                TimeSpan ts = new TimeSpan(DateTime.Now.Ticks -ticks);
                HttpContext.Current.Response.Headers.Set("ServerProcessTime", Math.Ceiling(ts.TotalMilliseconds).ToString());
            };

客户端在借助beforeSend和complete事件,实现code如下:

 $(["get", "post"]).each(function (i, ajaxType) {
        G[ajaxType] = function (option) {
            $.ajax({
                url: option.url,
                data: option.data,
                type: ajaxType,
                beforeSend: function () {
                    option.StartClientTime = new Date();
                },
                dataType: "json",
                cache: option.cache,
                async: option.async,
                success: function (d) {
                   alert(d)
                },
               
                complete: function (XMLHttpRequest, textStatus) {
                    var endClientTime = new Date();
                    try {
                        var logRequest = false;
                        if (option.url.indexOf("/Member/AAA") >= 0 ||
                            option.url.indexOf("/Member/BBB")>=0 ||
                            option.url.indexOf("/Member/CCC")>=0) {
                            logRequest = true;
                        }
                        if (logRequest) {
                            //记录请求时间
                            var costTime = endClientTime - (option.StartClientTime - 0);
                            var serverTime = XMLHttpRequest.getResponseHeader("ServerProcessTime");
                            console.log("Rquest " + option.url + " totlal cost time:" + costTime + " Server time:" + serverTime);
                            var logdata = {
                                ajaxUrl: option.url,
                                TotalTicks: costTime,
                                ServerTicks: serverTime
                            };
                          
                            $.post("/xxx/LogRequest", logdata);
                        }
                    } catch (e) {

                    }
                }
            });
        };
    });

最后在调用LogRequest把时间记录到日志系统中。

原文地址:https://www.cnblogs.com/majiang/p/6664707.html