We're using structured logging on all our services, so all logs are in json format. When a BackgroundService crashes, it prints a cleartext stacktrace onto STDOUT. I'd like to be able to catch exceptions from BackgroundServices, log them in a structured way and then exit the service. Is there a way to do that without using something like System.Exit()?
I've tried switching from IHostedService to BackgroundService because in that version, the service would just ignore the crashed background task, which is not what I wanted either. I'd like the whole system to crash but not to trash my structured output.
Could you enclose everything in the overridden ExecuteAsync()
in a try-catch block that handles this failure?
Maybe StopApplication()
could help?