Get Function name

  • Thread starter Thread starter Mike Oliszewski
  • Start date Start date
M

Mike Oliszewski

Is it possible for a c# function to get it's own name ? We have LOTS of
logging calls for which the programmer has to manually add the name of the
function as part of the output, often people copy code from one area to
another and then forget to update the name. It would be really slick if we
were able to programmatically get the function name without a huge
processing overhead.

Is this possible ? Is it possible to get a calling functions name ? Any
samples anywhere ?
 
Yes, this is!

Here is an snippet of one of the routine I use within my custom exception
(It contains more, but was simplified for clarity).
Playing with the stackFrameLevel, you can determine which routine within the
stack you want to get information from.

Hope this help
José


protected string BuildMsg( string Msg,
Status.Stat MsgStatus,
Severity.Level SeverLevel,
short stackFrameLevel)
{
int nDebLocation = 0;
try
{
// Convert severity to 1 char
string strCurrSeverity = Severity.ToShortString(SeverLevel);

// Get stack information (FileName, Method, Line#)
StackFrame stFrame = new StackFrame(stackFrameLevel, true);

}

string strFileName;
if ( stFrame.GetFileName() != null)
strFileName =
stFrame.GetFileName().Substring(stFrame.GetFileName().LastIndexOf(@"\")+1);
else
strFileName = "Unknown???";


// Build information
string strFullInfo = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff",
null) +
" [" + processInfo.MainModule.ModuleName + " - " +
strFileName + " - " + stFrame.GetMethod().Name +
"() - Line:" + (stFrame.GetFileLineNumber()).ToString() + "] " +
Environment.NewLine +
" [" + strCurrSeverity + ":" + ((int)MsgStatus).ToString("D5")
+ "] " + Msg + Environment.NewLine;


return strFullInfo;
}
catch (Exception ex)
{
return "Unable to build msg for logger. Err: " + ex.ToString() + ".
Dbg: " +
nDebLocation +
". Make sure the .PDB file has been copied in the Binary directory!";
}
}

You have to play with StackFrame class. It provides a whole lot of
information you can extract for your logging purpose.
 
Awsome, thank you!

José Joye said:
Yes, this is!

Here is an snippet of one of the routine I use within my custom exception
(It contains more, but was simplified for clarity).
Playing with the stackFrameLevel, you can determine which routine within the
stack you want to get information from.

Hope this help
José


protected string BuildMsg( string Msg,
Status.Stat MsgStatus,
Severity.Level SeverLevel,
short stackFrameLevel)
{
int nDebLocation = 0;
try
{
// Convert severity to 1 char
string strCurrSeverity = Severity.ToShortString(SeverLevel);

// Get stack information (FileName, Method, Line#)
StackFrame stFrame = new StackFrame(stackFrameLevel, true);

}

string strFileName;
if ( stFrame.GetFileName() != null)
strFileName =
stFrame.GetFileName().Substring(stFrame.GetFileName().LastIndexOf(@"\")+1);
else
strFileName = "Unknown???";


// Build information
string strFullInfo = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff",
null) +
" [" + processInfo.MainModule.ModuleName + " - " +
strFileName + " - " + stFrame.GetMethod().Name +
"() - Line:" + (stFrame.GetFileLineNumber()).ToString() + "] " +
Environment.NewLine +
" [" + strCurrSeverity + ":" + ((int)MsgStatus).ToString("D5")
+ "] " + Msg + Environment.NewLine;


return strFullInfo;
}
catch (Exception ex)
{
return "Unable to build msg for logger. Err: " + ex.ToString() + ".
Dbg: " +
nDebLocation +
". Make sure the .PDB file has been copied in the Binary directory!";
}
}

You have to play with StackFrame class. It provides a whole lot of
information you can extract for your logging purpose.
Mike Oliszewski said:
Is it possible for a c# function to get it's own name ? We have LOTS of
logging calls for which the programmer has to manually add the name of the
function as part of the output, often people copy code from one area to
another and then forget to update the name. It would be really slick if we
were able to programmatically get the function name without a huge
processing overhead.

Is this possible ? Is it possible to get a calling functions name ? Any
samples anywhere ?
 
Hi Mike,

Just as José and Robert suggested, there are 2 ways to get the current
method's name: Use StackFrame class and Use Reflection.
But StackFrame retrieves the file, method name, line number, and column
information from the debug symbols which was stored in .PDB file.
So StackFrame will be most informative with Debug build configurations. By
default, Debug builds include debug symbols, while Release builds do not.
If you still want to use StackFrame in Realse configuration, you need to
change the default build configuration for realse:
Project->Project properties, then chose configuration:Realse, select
"Build" tab page, change "Generate Debugging Information" to true.

I think the most suitable solution is use Reflection. Reflection can be
used to runtime dynamic get the assembly information which was stored in
assembly manifest.
So MethodBase.GetCurrentMethod().Name is an elegant way.

Hope this helps,

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
When I designed my Custom Exception, I decided to go with the StackFrame
because my goal was to hide all repetiting tasks within the Exception class.
The idea was to be able to throw exception or trace messages giving the
minimal amount of parameters. In fact, I just wanted to pass a string
explaning the problem and an ID of the problem.
Any other information is retrieved from within my custom exception class.
This includes Method name, file name, process name, line # within the file,
VSS file version and other.
In that sense, the easiest way was to use the StackFrame. This allowed me to
walk it and extract information about the correct caller.

José
 
Hi Jose,

Yes, you are right, StackFrame is more suitable for retriving current
executive statck information.
But Mike only want to get the current function's name, which I think
Reflection is a more elegant way. In any case, thanks for your information
about StackFrame.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top