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.

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top