1

I have a custom logger class which implements the ILogger interface. The custom logger is a separate assembly/nuget. I was trying to use stacktrace to find the name of the calling method but it seems it differs if used in the program versus a unit testing project. Is there a more convenient way to get the calling method e.g. the calling assembly method name?

public class MyClass {

   private void HelloWorld() {
        var myLoggerProvider = new LoggerProvider(Config);
        LoggerFactory.AddProvider(myLoggerProvider);
        var logger = LoggerFactory.CreateLogger<Program>();
        LogInformation("HelloWorld");
   }
}

// Inside custom logger

 ////...
     public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
       //   Get the calling function name
      var classFunction = new StackTrace(4).GetFrame(0).GetMethod().Name;
    }
 ///....
doorman
  • 15,707
  • 22
  • 80
  • 145
  • You could use calling information. See https://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method, the second answer shows how – ESG Dec 18 '20 at 13:43

0 Answers0