Logging filename, line number in logs. Do I need to pass the StackFrame?
-
07-09-2020 - |
문제
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()
).
제휴하지 않습니다 StackOverflow