如果是在桌面程序中只需要
_contextLog=ConsoleOut;
即可在控制台输出SQL语句可是在ASPNET中又该怎么办呢?
这时我想起了StringWriter用它就可以代替ConsoleOut帮我们接收输出的日志保存在一个StringBuilder里
于是构造一个辅助类
usingSystem;
usingSystemCollectionsGeneric;
usingSystemLinq;
usingSystemWeb;
usingSystemIO;
usingSystemText;
namespaceClowwindyModels
{
publicstaticclassLogHelper
{
publicstaticStringBuilderLog=newStringBuilder();
publicstaticTextWriterIn=newStringWriter(Log);
publicstaticstringGetAllLog()
{
InFlush();
returnLogToString();
}
publicstaticvoidClean()
{
Log=newStringBuilder();
In=newStringWriter(Log);
}
}
}
再添加一个页面logaspx用来显示日志
<%@PageLanguage=C#AutoEventWireup=true
CodeBehind=LogaspxcsInherits=ClowwindyLog%>
<!DOCTYPEhtmlPUBLIC//WC//DTDXHTMLTransitional//EN
transitionaldtd>
<htmlxmlns=>
<headrunat=server>
<title>SQLLog</title>
</head>
<body>
<formid=formrunat=server>
<asp:ButtonID=btn_Cleanrunat=serverText=清空
onclick=btn_Clean_Click/>
<div>
<asp:LiteralID=Literalrunat=server></asp:Literal>
</div>
</form>
</body>
</html>
usingSystem;
usingSystemCollectionsGeneric;
usingSystemLinq;
usingSystemWeb;
usingSystemWebUI;
usingSystemWebUIWebControls;
usingClowwindyModels;
namespaceClowwindy
{
publicpartialclassLog:SystemWebUIPage
{
protectedvoidPage_Load(objectsenderEventArgse)
{
if(RequestUserHostAddress!=)
{
ResponseEnd();
return;
}
LiteralText=LogHelperGetAllLog()Replace(\n\n<br/>);
}
protectedvoidbtn_Clean_Click(objectsenderEventArgse)
{
LogHelperClean();
LiteralText=null;
}
}
}
最后在所有new DataContext的地方
加上_contextLog = LogHelperIn:
publicRepository()
{
_context=newTDataContext();
_contextLog=LogHelperIn;
}
打开logaspx即可看到之前执行的SQL语句