Friday, October 09, 2015

Logging the Stack

I don't know, just thought I might need this again someday:

void LogStack()
{
StackTrace stackTrace = new StackTrace(true);
var thisMethod = stackTrace.GetFrames().Skip(1).First().GetMethod().Name;
var stack = stackTrace.GetFrames().Skip(2).Select(f => string.Format("{0}[{1}]", f.GetMethod().Name, f.GetFileLineNumber())).ToArray();
var result = string.Join(" < ", stack);
Log.Warn(logData, "{0} called from {1}", thisMethod, result);
}