问题
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?
回答1:
NLog 4.5 supports the scenario out of the box (Currently in BETA). 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
回答2:
I solved my issue stacking up message logs in a MemoryTarget then saving it (Flushing) when needed. Look:
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>
....
After run it, the output will be:
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.
回答3:
A bit late, but this my (reduced) config:
<?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>
This will queue all messages (max=32) below warning level. If a message above or equal to error will be logged, the queue will be flushed.
C# Testcode with the above config. Only the warn message will be visible. If either the error or the fatal message are added all messages will be visible.
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();
来源:https://stackoverflow.com/questions/47020718/how-to-stack-up-log-messages-and-log-them-just-when-an-exception-occurs