我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用logging._srcfile()。
def _inject_into_logger(name, code, namespace=None): # This is a hack to fool the logging module into reporting correct source files. # It determines the actual source of a logging call by inspecting the stack frame's # source file. So we use this `eval(compile())` construct to "inject" our additional # methods into the logging module. if namespace is None: namespace = {} eval( compile( code, logging._srcfile, 'exec' ), namespace ) setattr(logging.Logger, name, namespace[name]) # Add `trace()` level to Logger
def findCaller(self): """ 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 _srcfiles = [os.path.normcase(__file__), logging._srcfile] rv = "(unknown file)", 0, "(unknown function)" while hasattr(f, "f_code"): co = f.f_code filename = os.path.normcase(co.co_filename) if filename in _srcfiles: f = f.f_back continue rv = (co.co_filename, f.f_lineno, co.co_name) break return rv
def configlog4download(logger, db_session, download_id, isterminal): """configs for download and returns the handler used to store the log to the db and to a tmp file. The file is accessible via logger..baseFilename """ # https://docs.python.org/2/howto/logging.html#optimization: logging._srcfile = None logging.logThreads = 0 logging.logProcesses = 0 # FIXME above: move elsewhere (maybe restoring defaults?) logger.setLevel(logging.INFO) # necessary to forward to handlers # custom StreamHandler: count errors and warnings: dbstream_handler = DbStreamHandler(db_session, download_id) logger.addHandler(dbstream_handler) if isterminal: # configure print to stdout (by default only info and critical messages) logger.addHandler(SysOutStreamHandler(sys.stdout)) return dbstream_handler # def configlog4stdout(logger): # logger.setLevel(logging.INFO) # necessary to forward to handlers # # configure print to stdout (by default only info and critical messages): # logger.addHandler(SysOutStreamHandler(sys.stdout))
def setup(mute_stdout=False): # logging.basicConfig() if mute_stdout: handler = logging.NullHandler() else: formatter_str = '%(asctime)s %(levelname)s %(message)s' handler = logging.StreamHandler() handler.setFormatter(logging.Formatter(formatter_str)) # Add handler to logger logger = logging.getLogger(_product_name) logger.addHandler(handler) # disable unnecessary information capture logging.logThreads = 0 logging.logProcesses = 0 # to make sure each log record does not have a source file name attached # pylint: disable=protected-access logging._srcfile = None # pylint: enable=protected-access
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False, attachment=None): """ Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record. """ sinfo = None if logging._srcfile: # IronPython doesn't track Python frames, so findCaller raises an # exception on some versions of IronPython. We trap it here so that # IronPython can use logging. try: fn, lno, func, sinfo = self.findCaller(stack_info) except ValueError: # pragma: no cover fn, lno, func = '(unknown file)', 0, '(unknown function)' else: fn, lno, func = '(unknown file)', 0, '(unknown function)' if exc_info and not isinstance(exc_info, tuple): exc_info = sys.exc_info() record = self.makeRecord( self.name, level, fn, lno, msg, args, exc_info, func, extra, sinfo ) record.attachment = attachment self.handle(record)
def monkeypatch_findCaller(): if __file__.lower()[-4:] in ['.pyc', '.pyo']: _wrapper_srcfile = __file__.lower()[:-4] + '.py' else: _wrapper_srcfile = __file__ _wrapper_srcfile = normcase(_wrapper_srcfile) def findCaller(self, stack_info=False): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() #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 rv = "(unknown file)", 0, "(unknown function)", None while hasattr(f, "f_code"): co = f.f_code filename = normcase(co.co_filename) if filename == _wrapper_srcfile or filename == logging._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 logging.Logger.findCaller = findCaller