Tolyandre/serilog-throw-context-enricher

Scenario of prevent recursion

Closed this issue · 2 comments

Could you please provide a scenario where possible recursion behavior in this scope?

  // prevent recursion if an exception is thrown inside our enricher scope
  bool alreadyEnriched = true;
  EnrichedLogEvents.GetValue(logEvent, _ =>
  {
      alreadyEnriched = false;
      return null;
  });

I am confused by this as well. I guess it is more of a defensive coding.

Hi @evgenbakai and @maxisam, I apologise for the delayed response, I haven't been on GitHub for a while.

As far as I remember, the recursion occurs when an exception is thrown inside the ThrowContextEnricher scope. It gets into context and invokes itself.

using (LogContext.Push(new ThrowContextEnricher()))
{
     try
     {
           throw new Exception();
     }
    catch(Exception ex)
     {
          Log.Error(ex, "");
     } 
}

There is a unit test for this scenario https://github.com/Tolyandre/serilog-throw-context-enricher/blob/master/Serilog.ThrowContext.Tests/PreventStackOverflowTests.cs#L22