Chris Hayes
Chris Hayes

Reputation: 4037

nLog, Is there a way to log a tail of trace level up messages on error?

I am looking for a way to dump a tail of trace level logging (and up) when an error occurs.

Is there a way to do this?

Upvotes: 0

Views: 154

Answers (1)

oakio
oakio

Reputation: 1898

Sorry, but NLog has no built-in target for this feature. But you can easy implement this! Create custom target based on CompoundTargetBase class!

Here my simple prototype:

class TracedErrorTarget : CompoundTargetBase
{
    private int _head;
    private LogEventInfo[] _traceTail; // ring buffer

    protected override void Write(LogEventInfo logEvent)
    {
        if (logEvent.Level == LogLevel.Trace)
        {
            SaveTrace(logEvent);
            return;
        }

        if (logEvent.Level == LogLevel.Error)
        {
            LogEventInfo tracedLogEvent = PrepareTracedErrorEvent(logEvent);
            base.Write(tracedLogEvent);
            return;
        }

        base.Write(logEvent);
    }

    private void SaveTrace(LogEventInfo logEvent)
    {
        int traceDepth = _traceTail.Length;

        _traceTail[_head] = logEvent;
        _head = (_head + 1) % traceDepth;
    }

    private LogEventInfo PrepareTracedErrorEvent(LogEventInfo logEvent)
    {
        // prepare LogEventInfo with trace tail
        throw new System.NotImplementedException();
    }
}

Upvotes: 2

Related Questions