Last active
August 16, 2023 07:58
-
-
Save ramonsmits/f85329c22be91011201eaf35b6031a9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ILogger logger = null;// Get logger | |
var appDomain = AppDomain.CurrentDomain; | |
appDomain.UnhandledException += (sender, ea) => Log.Fatal((Exception)ea.ExceptionObject, "UnhandledException"); | |
if (logger.IsEnabled(LogEventLevel.Debug)) | |
{ | |
appDomain.FirstChanceException += (sender, ea) => | |
{ | |
var ex = ea.Exception; | |
ex.SetStackTrace(new StackTrace(1)); // Optional, add stacktrace info but requires `ExceptionExtensions` | |
logger.Debug(ex, "FirstChanceException {type} {message}", ex.GetType(), ex.Message); | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Linq.Expressions; | |
using System.Reflection; | |
static class ExceptionExtensions | |
{ | |
public static Exception SetStackTrace(this Exception target, StackTrace stack) => _SetStackTrace(target, stack); | |
static readonly Func<Exception, StackTrace, Exception> _SetStackTrace = new Func<Func<Exception, StackTrace, Exception>>(() => | |
{ | |
var target = Expression.Parameter(typeof(Exception)); | |
var stack = Expression.Parameter(typeof(StackTrace)); | |
var traceFormatType = typeof(StackTrace).GetNestedType("TraceFormat", BindingFlags.NonPublic)!; | |
var toString = typeof(StackTrace).GetMethod("ToString", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { traceFormatType }, null)!; | |
var normalTraceFormat = Enum.GetValues(traceFormatType).GetValue(0); | |
var stackTraceString = Expression.Call(stack, toString, Expression.Constant(normalTraceFormat, traceFormatType)); | |
var stackTraceStringField = typeof(Exception).GetField("_stackTraceString", BindingFlags.NonPublic | BindingFlags.Instance)!; | |
var assign = Expression.Assign(Expression.Field(target, stackTraceStringField), stackTraceString); | |
return Expression.Lambda<Func<Exception, StackTrace, Exception>>(Expression.Block(assign, target), target, stack).Compile(); | |
})(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment