net5 disable stderr output if I handle AppDomain.CurrentDomain.UnhandledException

9/2/2021

I'm in the process of setting up FluentD in a cloud application in development. I want to analyse UnhandledExceptions in the logs so that I can add appropriate error traps where I may have missed them.

My net5 app writes unhandled exceptions to STDERR which seems to be the standard behaviour of the framework - these turn up in fluentd under a 'fluent.warn' tag - I just log these to a fluent.warn.log. I actually want to capture these errors into my application log instead - this is set up to read json events from Kubernetes container logs using the CRI parse plugin.

To make my unhandled exception appear in my app log, I have added an UnhandledException handler as follows:

            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
            {
                logger.LogError(e.ExceptionObject as Exception, $"Unhandled Exception, IsTerminating={e.IsTerminating}");
            };

This does work, but I now have a structured event in my application log, and an unstructured text output in STDERR (appears in my fluent.warn.log) because net5 still prints out the UnhandledException to STDERR even though I added a handler.

Is there a way to suppress the default output on STDERR if I already logged the error via the UnhandledException callback?

Alternatively, since fluentd happily reads these events anyway, is there a way to change the format of the text written to STDERR under these circumstances (I already have an AddJsonConsole, but the output on STDERR bypasses that).

I will probably be able to get rid of all of the UnhandledExceptions in due course anyway, but I really want to effectively capture any leaks by setting up the logging properly.

Thanks in advance for your help.

-- Mark Rabjohn
.net-5
fluentd
kubernetes

0 Answers