Question

Currently, I pass the StackFrame to grab the current file/line number:

Log.Message(new StackFrame(0, true), "FAILED to start cooling.");

Where in the Log class is:

public void Message(StackFrame Callstack, string message)
{
    string logMessage = string.Format("{0} {1}:{2} {3} \t{4}", DateTime.Now.ToString(), Callstack.GetFileName(), Callstack.GetFileLineNumber(), Callstack.GetMethod(), message);

    //Write to console
    Console.WriteLine(logMessage);

    //write to file
}

Do I need to pass the StackFrame each time to the Log.Message() method? Can this be done in the method it self without passing it? Is there a simpler method?

Thanks.

Was it helpful?

Solution

You can do:

public void Message(string message) {
    StackFrame callstack = new StackFrame(1, true);
    // ...
}

The 1 skips the Message method part of the callstack and gets it caller.

OTHER TIPS

You can. The first constructor parameter of StackFrame defines the number of frames to skip. So when creating the object instance within Message() just pass 1 and it will show the calling frame (where you used the call to Message()).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top