简体   繁体   中英

StackOverflowException in Serilog Enricher

I'm writing an enricher for Serilog and I want to add a property that may trigger a new log event, in practice:

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
    ISession session = /* HttpContext.Session */;
    logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ValueFromSession", session.GetString("ValueFromSession")));
    /* other properties ... */
}

I want to be able to add a value from my http session to my logs, so I use LogContext.PushProperties with a custom enricher. ASP.NET Core logs a warning whenever an expired session is read, which triggers my enricher, but whenever I attempt to read from the session in the enricher it warns me about the expired session, which triggers a new instance of my enricher (ad infitum). This causes a StackOverflowException which does not seem to be catchable with a try block.

Is there any way to disable logging when in an Enrich method? Or can I detect this kind of recursion somehow (other than parsing a stacktrace)?

I encountered this problem with my custom ILogger implementation (not using Serilog). It happens anytime the Session object is accessed. I managed to fix this by adding DataProtection with persisted keys to my application on startup.

services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo("keys"));

I haven't gone too deeply into the implementation details, but from what I see in the DistributedSession code, the "Accessing expired session" message is logged when an old session key is detected. The problem here is that the logging happens before the isAvailable flag is set to true which causes the recursion. I don't know why adding DataProtection avoids this issue, but it could that the DataProtection causes the _isNewSessionKey to be always true .

Another workaround suggested in GitHub would be to add a middleware to save the Session items you want to log to HttpContext.Items. Then retrieve those items in your logger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM