我有一个执行大量 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 支持开箱即用的场景。这将在警告/错误/致命发生时显示最后 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
关于c# - 如何堆叠日志消息并在发生异常时记录它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47020718/