如何在发生异常时堆叠日志消息并记录它们?

时间:2017-10-30 17:08:52

标签: c# logging log4net nlog

我有一个执行一堆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是否支持这种情况吗?如果没有,如何实施呢?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

我解决了我在MemoryTarget中堆叠消息日志然后在需要时保存它(Flushing)的问题。看:

public class Program
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    static void Main(string[] args)
    {
        try
        {
            logger.Log(LogLevel.Error, "Start of the process");
            // Inside Business class i have a lot of other logger.log() calls
            // Inside the business class a have a lot of DAOs that calls logger.log()
            // In ither words, all the calls to logger.log() will be stacked up
            Business b = new Business();
            b.DoSomethig();
            logger.Debug("End of the Process.");
        }
        catch (Exception )
        {
            var target = (MemoryTarget)LogManager.Configuration.FindTargetByName("MemoTarget");
            var logs = target.Logs;

            // Get all the logs in the "stack" of log messages
            foreach (string s in target.Logs)
            {
                Console.Write("logged: {0}", s);
            }
        }

    }
}

nlog.config:

<targets>
    <target xsi:type="Memory" name="MemoTarget" layout="${date:format=dd-MM-yyyy HH\:mm\:ss} | ${callsite} | ${message}" />
 ...
</targets>
...
<rules>
    <logger name="*" minlevel="Debug" writeTo="MemoTarget" />
</rules>
....

运行后,输出将为:

logged: 30-10-2017 20:12:36 | NLog_Tests.Program.Main | Start of the process 
logged: 30-10-2017 20:12:36 | NLog_Tests.Business.DoSomethig | Some business rule was executed
logged: 30-10-2017 20:12:36 | NLog_Tests.DAOClass.ExecuteCommand | some sql was executed
logged: 30-10-2017 20:12:36 | NLog_Tests.Program.Main | End of the Process.

答案 2 :(得分:1)

有点晚了,但这是我的(减少的)配置:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <targets async="true">
    <wrapper-target xsi:type="BufferingWrapper" name="buffer" bufferSize="32" flushTimeout="100">
      <wrapper-target xsi:type="PostFilteringWrapper">
        <defaultFilter>level >= LogLevel.Warn</defaultFilter>
        <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
        <target xsi:type="ColoredConsole" />
      </wrapper-target>
    </wrapper-target>
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="buffer" />
  </rules>
</nlog>

这会将所有消息(max = 32)排在警告级别以下。如果将记录高于或等于错误的消息,则将刷新队列。

使用上述配置的C#Testcode。只有警告消息才会显示。如果添加了错误或致命消息,则所有消息都将可见。

LogManager.Configuration = new XmlLoggingConfiguration(@"cfg\NLog.xml", false);
LogManager.ReconfigExistingLoggers();

LOG.Trace("trace");
LOG.Debug("debug");
LOG.Info("info");
LOG.Warn("warn");
//LOG.Error("error");
//LOG.Fatal("fatal");

LogManager.Flush();
LogManager.Shutdown();