I had the need to log the current stack trace in a method to figure out which event handler calls the method in order to solve a bug. The method is commonly used in a number of different handlers. I find in the log that this method is called twice in a request that should only call it once. Logging the current stack trace in the method would tell me which handler calls it the second time.
I’ve never had the need to get the current stack trace in the code apart from when there’s a thrown exception. It turns out to be quite simple, here’s how.
var stackTrace = new System.Diagnostics.StackTrace();
_logger.LogInformation($"Current stack trace: {stackTrace.ToString()}");