Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current method and class without exception and without using reflection in C#

Tags:

c#

.net

I am wanting to log out some INFO logging in a method, and I am not wanting to use reflection to get hold of the Class and Method name.

For Error logging I can get the stack off the exception but how do I do this without an exception to get the StackTrace off?

like image 975
Mr_road Avatar asked Dec 10 '22 08:12

Mr_road


1 Answers

You can get the information about the caller using caller attributes

public void Log(Exception ex, [CallerFilePath]string callerFilePath = null, [CallerMemberName]string callerMemberName = null, [CallerLineNumber]int callerLineNumber = 0)
{
    Console.WriteLine($"Message: {ex.Message} # File: {callerFilePath} # Line: {callerLineNumber} # Member: {callerMemberName}"  );
}

When the method is called the information about the caller will be passes to you by the compiler, you don't need to manually specify the parameters.

like image 118
Titian Cernicova-Dragomir Avatar answered May 18 '23 11:05

Titian Cernicova-Dragomir