如何堆叠日志消息并仅在发生异常时对其进行日志记录? [英] How to stack up log messages and log them just when an exception occurs?
问题描述
我有一个执行一堆SQL命令的业务流程.我想将这些sql命令堆栈"到堆栈中,并在发生异常时将它们写到DB中,让我用一些代码来解释它
I have a business process that executes a bunch of SQL Commands. I want to "stack up" these sql commands in a stack and write them to DB just when an exception occurs, let me explain it with some code
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是否支持这种情况?如果没有,该如何实施?
Does anyone know if the Log4Net or NLog supports this scenario? If not, How to implement it?
推荐答案
NLog 4.5支持开箱即用的方案.当发生警告/错误/致命(导致自动刷新触发)时,将显示最后50条消息:
NLog 4.5 supports the scenario out of the box. This will show the last 50 messages when a warning/error/fatal occurs (Causing the auto-flush to trigger):
<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没有溢出动作.相反,可以滥用AsyncWrapper:
NLog 4.4 (and older) needs some more help, as BufferingWrapper doesn't have an overflowAction. Instead the AsyncWrapper can be abused:
<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
这篇关于如何堆叠日志消息并仅在发生异常时对其进行日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!