Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

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()).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top