记录数据库执行情况来分析数据库查询性能问题(四)

2014-11-24 08:19:30 · 作者: · 浏览: 24
ew Code
public class ContextFactory
{
private static IContextHandler _ContextHandler;
private static object _lockPad = new object();
private static bool _Init = false;

///
/// 注册上下文句柄
///

///
public static void RegisterContextHandler(IContextHandler handler)
{
if (_Init == false)
{
lock (_lockPad)
{
if (_Init == false)
{
_ContextHandler = handler;
_Init = true;
}
}
}

}

///
/// 获取当前上下文
///

///
public static IContext GetContext()
{
if (_ContextHandler != null)
{
return _ContextHandler.GetContext();
}
else
{
return null;
}
}

///
/// 设置当前上下文(慎重使用)
///

public static void SetContext(IContext context)
{
_ContextHandler.SetContext(context);
}
}
复制代码


在应用程序中注册web上下文句柄,其实这里还可以注册很多类似的上下文句柄,比如异步信息等,有机会以后再分享。




protected void Application_Start()
{

SimpleWebContextHandler handler = new SimpleWebContextHandler();
ContextFactory.RegisterContextHandler(handler);
....
}
复制代码

第七:查看结果,这里只是记录在文本文件中,我们可以将这些日志记录在日志数据库中,然后通过各种语句产生不同的数据,比如查询访问时间最长的10条语句,使用次数最多的10条语句,某次请求中消耗时间最长的语句等等。


2012-02-22 15:33:46,545 [6] ERROR ApplicationLog.CommonLogger [(null)] - 请求id:0e6b7634-0f8e-49ee-8c1f-6e6700a143a9
请求IP:127.0.0.1
查询时间:20
查询SQL:select * from Customers

2012-02-22 15:33:46,592 [6] ERROR ApplicationLog.CommonLogger [(null)] - 请求id:0e6b7634-0f8e-49ee-8c1f-6e6700a143a9
请求IP:127.0.0.1
查询时间:0
查询SQL:select * from Categories

2012-02-22 15:33:46,592 [6] ERROR ApplicationLog.CommonLogger [(null)] - 请求id:0e6b7634-0f8e-49ee-8c1f-6e6700a143a9
请求IP:127.0.0.1
查询时间:0
查询SQL:select * from Orders



这里的内容主要是针对数据库访问,后面会利用AOP来记录每个方法的执行情况,无论此方法里面的具体操作是什么,统一记录,为程序员分析页面程序提供更加准备的信息。


摘自 min.jiang