-2

I am implementing simple logging, and I would like to do something like below

public int SomeMethod(int x)
{
  Log(SomeMethod,"here is a log entry);
}

In the Log method, I would like to parse out the class name from the method and print to the log file the method name and class name.

Is it possible to do something that would look as simple as above or something similar?

Jason Smith
  • 373
  • 2
  • 6
  • 20
  • 1
    You could use a delegate function to pass an actual function, defined either locally in the SomeMethod scope or more broadly in the class or similar that contains SomeMethod. – FooAnon Jan 25 '19 at 23:15

2 Answers2

-1

Try this with Reflection

var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
var currentCalssName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

Or you can implement your Log method like these

public static void Log<TCallerClass>(string text, [CallerMemberName]string method = "")
{
var callerMethodName = method;
var callerCalssName = typeof(TCallerClass).FullName;
}

Usage : Log<YourClass>("here is a log entry");

public static void Log(string text)
{
var stackFrame = new StackFrame(1, true);
var callerMethodName = stackFrame.GetMethod().Name;
var callerCalssName = stackFrame.GetMethod().DeclaringType.Name;
}

Usage : Log("here is a log entry");

NaDeR Star
  • 647
  • 1
  • 6
  • 13
-1

you could use nameof if you are using C# 6 or later

public int SomeMethod(int x)
{
  Log(nameof(SomeMethod), "here is a log entry");
}
Jorge
  • 57
  • 2
  • 7