-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?

1
  • 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. Commented Jan 25, 2019 at 23:15

2 Answers 2

-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");
}
Sign up to request clarification or add additional context in comments.

Comments

-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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.