0

I have an ASP.NET MVC application and would like to log the names of all the involved methods, for certain user flows on the website.

The following code does that, but it stops at the root/first triggered method:

public string GetStackTraceMethods()
{
    List<string> stackTraceMethods = new List<string>();
    StackTrace stackTrace = new StackTrace();
    string methodName = string.Empty;

    // These are the default/framework methods that I do not want to log. So, excluding them.
    List<string> methodNamesToIgnore = new List<string> {
              "GetStackTraceMethods", "MoveNext", "Start",
              "lambda_method", "BuildProduct", "BuildProducts",
              "b__2", ".ctor", "ToList"
            };

    foreach (StackFrame frame in stackTrace.GetFrames())
    {
        methodName = frame.GetMethod().Name;

        if (methodName == "InvokeActionMethod")
        {
            break;
        }
        else if (methodNamesToIgnore.Any(x => x == methodName))
        {
            continue;
        }
        else
        {
            stackTraceMethods.Add(frame.GetMethod().Name);
        }
    }

    return string.Join(" < ",  stackTraceMethods);
}

This returns a result like this:

Some_Service_Method_2 < Some_Service_Method_1 < Controller_Method

Is it possible to get the controller's name also from the stack trace, so that I can include that in the list?

UPDATE: the GetStackTraceMethods() method is placed in the bottom level of the flow. i.e it is placed in the same class as Some_Service_Method_2

@Chetan's comment worked. It gives the class name of that method.

sukesh
  • 2,379
  • 12
  • 56
  • 111
  • 1
    https://stackoverflow.com/a/18248594/6527049 is this helpful? – Vivek Nuna Dec 12 '21 at 06:41
  • 1
    Look into `DefaultControllerFactory`, IController CreateController, here you can easily log the current controller. Save it in ContextItems. – Charles Dec 12 '21 at 06:41
  • 1
    `frame.GetMethod().DeclaringType.Name` – Chetan Dec 12 '21 at 06:49
  • "I have an ASP.NET MVC application and would like to log the names of all the involved methods, for certain user flows on the website." - you don't need a StackTrace for that. Getting a StackTrace is a **very expensive** operation. There are much better ways of getting an ASP.NET MVC controller name at runtime, such as using `this.ControllerContext.RouteData.Values["controller"]`. – Dai Dec 12 '21 at 06:55
  • I did the **EXACT** same thing for a Winform app - I needed to do it for troubleshooting, ended up good for telemetry: https://stackoverflow.com/q/30326673/495455 Tip: have a config switch you can turn it off, the logs grow large and affect performance. I do it with DEBUG mode releases. Alternatively consider AppInsights. – Jeremy Thompson Dec 12 '21 at 07:04

0 Answers0