Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stack up log messages and log them just when an exception occurs?

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?

like image 392
Ewerton Avatar asked Oct 30 '17 17:10

Ewerton


1 Answers

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

like image 200
Rolf Kristensen Avatar answered Sep 30 '22 17:09

Rolf Kristensen