我有一个执行一堆SQL命令的业务流程.我想在堆栈中“堆叠”这些sql命令并在发生异常时将它们写入DB,让我用一些代码解释一下
public void BusinessMethod()
{
Log.Initialize(); // Clear the stack
try
{
Method1ThatExecutesSomeSQLs();
Method2ThatExecutesSomeSQLs();
Method3ThatExecutesSomeSQLs();
}
catch(Expection ex)
{
// if some exception occured in any Method above, them i write the log, otherwise, i dont want to log anything
Log.Write();
}
}
//Example of some Method that executes SQL's
public void Method1ThatExecutesSomeSQLs()
{
string sql = "select * from table";
ExecuteSQL(sql);
Log.StackUp("The following sql command was executed: " + sql); //Just stack up, dont write!
}
有谁知道Log4Net或NLog是否支持这种情况?如果没有,如何实施呢?
解决方法:
NLog 4.5支持开箱即用的场景(目前在BETA中).这将显示警告/错误/致命发生时的最后50条消息(导致自动刷新触发):
<target name="consoleWarn" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Warn" >
<target xsi:type="BufferingWrapper" overflowAction="Discard" bufferSize="50">
<target xsi:type="Console" layout="${level}:${message}" />
</target>
</target>
NLog 4.4(及更早版本)需要更多帮助,因为BufferingWrapper没有overflowAction.而是可以滥用AsyncWrapper:
<target name="consoleWarn" xsi:type="AutoFlushWrapper" condition="level >= LogLevel.Warn" >
<target xsi:type="BufferingWrapper" bufferSize="500">
<target xsi:type="AsyncWrapper" queueLimit="50" overflowAction="Discard" fullBatchSizeWriteLimit="1" timeToSleepBetweenBatches="2000000000">
<target xsi:type="Console" layout="${level}:${message}" />
</target>
</target>
</target>
另见https://github.com/NLog/NLog.Extensions.Logging/issues/127