using System;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

 

namespace ClassLibrary1
{
    public class SqlPerformanceMonitorModule : IHttpModule
    {

        static string[] QuerySeparator = new string[] { Environment.NewLine + Environment.NewLine };

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += delegate(object sender, EventArgs e)
            {
                HttpContext httpContext = ((HttpApplication)sender).Context;
                httpContext.Items["linqToSqlLog"] = new StringWriter();
            };

            context.PostRequestHandlerExecute += delegate(object sender, EventArgs e)
            {
                HttpContext httpContext = ((HttpApplication)sender).Context;
                HttpResponse response = httpContext.Response;

                if (response.ContentType == "text/html")
                {

                    var log = (StringWriter)httpContext.Items["linqToSqlLog"];

                    var queries = log.ToString().Split(QuerySeparator, StringSplitOptions.RemoveEmptyEntries);

                    RenderQueriesToResponse(response, queries);
                }
            };
        }
        void RenderQueriesToResponse(HttpResponse response, string[] queries)
        {

            response.Write("<div class='PerformanceMonitor'>");
            response.Write(string.Format("<b>Executed {0} SQL {1}</b>", queries.Length, queries.Length == 1 ? "query" : "queries"));

            response.Write("<ol>");

            foreach (var entry in queries)
                response.Write(string.Format("<li>{0}</li>", entry));
            response.Write("</ol>");
            response.Write("</div>");

        }
        public void Dispose() { /* 사용안함*/ }
    }
}

web.config 의 system.web 에 httpModules 추가
<add name="SqlPerf" type="네임스페이스.SqlPerformanceMonitorModule, 어셈블리이름" />

신고

'Linq' 카테고리의 다른 글

Linq query log  (0) 2011.04.08
Linq Group by 절  (0) 2011.03.23
Linq용 쿼리분석기 LinqPad  (0) 2011.03.11
Linq로 Left Outer Join  (0) 2010.10.29
by 화니뿡뿡 2011.04.08 10:36
| 1 2 3 4 |

티스토리 툴바