cdub
cdub

Reputation: 25731

Grabbing the function and filename in C#

Is there a way to grab the function name and file name when I'm inside a function? I'm trying to add log files all over the place like so, and want to be able to just copy and paster my logfile line of code in certain functions:

public class NewCorrGenerator
{
    public void Start()
    {
        bool rc = true;

        myLogFile.InfoToFileWithTime("NewCorrGenerator - Start", appContext);

        etc.....
    }
}

As you can see is there a way to grab the class name and function name in a string and output it to myLogFile function?

Upvotes: 2

Views: 1010

Answers (5)

greenoldman
greenoldman

Reputation: 21082

I know this is an old question, but the need is still relevant. So for the record, easy way with new tools -- CallerMemberName and CallerFilePath.

Upvotes: 1

Mario
Mario

Reputation: 3445

You can use reflection to get what you need. Here is a way to get the method name: Retrieving the calling method name from within a method

I would consider doing something else though - either interception or code generation that hardcodes class/method names in. If you do end up using StackTrace it may be a good idea to surround the logging code with compiler debug directives.

Upvotes: 0

goric
goric

Reputation: 11905

You can use the System.Diagnostics.StackTrace and System.Diagnostics.StackFrame classes to retrieve information about the currently executing code:

var trace = new StackTrace(true);
var frame = trace.GetFrame(0);  // current frame
var lineNumber = frame.GetFileLineNumber();
var method = frame.GetMethod().Name;
var className = frame.GetMethod().ReflectedType.Name;

Upvotes: 2

cadrell0
cadrell0

Reputation: 17327

You can use GetCurrentMethod. This will return an object of type MethodBase. The Name property to get the name of the method. DeclaringType will give you the class. This isn't the same as the file name, but it should be close if you use one type per file.

Upvotes: 1

Icemanind
Icemanind

Reputation: 48726

What you need is called an Interceptor. The most popular framework for this is PostSharp. Its a commercial product that would do everything you need. If you want to write your own, try looking at this article

Upvotes: 0

Related Questions