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

我有一个执行一堆SQL命令的业务流程。 我想在堆栈中“堆叠”这些sql命令并在发生exception时将它们写入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支持开箱即用的场景(目前在BETA中)。 这将显示发生警告/错误/致命时的最后50条消息(导致自动刷新触发):

      

NLog 4.4(及更早版本)需要更多帮助,因为BufferingWrapper没有overflowAction。 而是可以滥用AsyncWrapper:

        

另请参见https://github.com/NLog/NLog.Extensions.Logging/issues/127

我解决了我在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:

   ...  ...    .... 

运行后,输出将是:

 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. 

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

      level >= LogLevel.Warn          

这会将所有消息(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();