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!
}
Does anyone know if the Log4Net or NLog supports this scenario? If not, How to implement it?
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 (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>
See also https://github.com/NLog/NLog.Extensions.Logging/issues/127
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With