From 41e4ad5d1d64a7d57bf83dc44cffe327edcfa991 Mon Sep 17 00:00:00 2001 From: Andy Haden Date: Mon, 27 Jan 2020 21:10:47 -0800 Subject: [PATCH] logging: Vendor findCaller for correct stack frame info in logs --- common/logging_extra.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/common/logging_extra.py b/common/logging_extra.py index d573327806..64da0d0deb 100644 --- a/common/logging_extra.py +++ b/common/logging_extra.py @@ -118,6 +118,42 @@ class SwagLogger(logging.Logger): else: self.info(evt) + def findCaller(self, stack_info=False, stacklevel=1): + """ + Find the stack frame of the caller so that we can note the source + file name, line number and function name. + """ + f = sys._getframe(3) + #On some versions of IronPython, currentframe() returns None if + #IronPython isn't run with -X:Frames. + if f is not None: + f = f.f_back + orig_f = f + while f and stacklevel > 1: + f = f.f_back + stacklevel -= 1 + if not f: + f = orig_f + rv = "(unknown file)", 0, "(unknown function)", None + while hasattr(f, "f_code"): + co = f.f_code + filename = os.path.normcase(co.co_filename) + if filename == _srcfile: + f = f.f_back + continue + sinfo = None + if stack_info: + sio = io.StringIO() + sio.write('Stack (most recent call last):\n') + traceback.print_stack(f, file=sio) + sinfo = sio.getvalue() + if sinfo[-1] == '\n': + sinfo = sinfo[:-1] + sio.close() + rv = (co.co_filename, f.f_lineno, co.co_name, sinfo) + break + return rv + if __name__ == "__main__": log = SwagLogger()