Python logging.currentframe() Examples

The following are 11 code examples of logging.currentframe(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logging , or try the search function .
Example #1
Source File: logging.py    From fastapi-realworld-example-app with MIT License 9 votes vote down vote up
def emit(self, record: logging.LogRecord) -> None:  # pragma: no cover
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = str(record.levelno)

        # Find caller from where originated the logged message
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:  # noqa: WPS609
            frame = cast(FrameType, frame.f_back)
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level, record.getMessage(),
        ) 
Example #2
Source File: log.py    From docker-python with Apache License 2.0 6 votes vote down vote up
def findCaller(self, stack_info=False):
        f = logging.currentframe()
        f = f.f_back
        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 in _ignore_srcfiles:
                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 
Example #3
Source File: logging_util.py    From zulip with Apache License 2.0 6 votes vote down vote up
def find_log_caller_module(record: logging.LogRecord) -> Optional[str]:
    '''Find the module name corresponding to where this record was logged.

    Sadly `record.module` is just the innermost component of the full
    module name, so we have to go reconstruct this ourselves.
    '''
    # Repeat a search similar to that in logging.Logger.findCaller.
    # The logging call should still be on the stack somewhere; search until
    # we find something in the same source file, and that should give the
    # right module name.
    f = logging.currentframe()
    while True:
        if f.f_code.co_filename == record.pathname:
            return f.f_globals.get('__name__')
        if f.f_back is None:
            return None
        f = f.f_back 
Example #4
Source File: log.py    From st2 with Apache License 2.0 6 votes vote down vote up
def find_caller(stack_info=None):
    """
    Find the stack frame of the caller so that we can note the source file name, line number and
    function name.

    Note: This is based on logging/__init__.py:findCaller and modified so it takes into account
    this file - https://hg.python.org/cpython/file/2.7/Lib/logging/__init__.py#l1233
    """
    rv = '(unknown file)', 0, '(unknown function)'

    try:
        f = logging.currentframe().f_back
        while hasattr(f, 'f_code'):
            co = f.f_code
            filename = os.path.normcase(co.co_filename)
            if filename in (_srcfile, logging._srcfile):  # This line is modified.
                f = f.f_back
                continue
            rv = (filename, f.f_lineno, co.co_name)
            break
    except Exception:
        pass

    return rv 
Example #5
Source File: util.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 6 votes vote down vote up
def setup_logging(streams=(sys.stderr,)):
  """Configures Python logging the way the TensorBoard team likes it.

  This should be called exactly once at the beginning of main().

  Args:
    streams: An iterable of open files. Logs are written to each.

  :type streams: tuple[file]
  """
  # NOTE: Adding a level parameter to this method would be a bad idea
  #       because Python and ABSL disagree on the level numbers.
  locale.setlocale(locale.LC_ALL, '')
  tf.logging.set_verbosity(tf.logging.WARN)
  # TODO(jart): Make the default TensorFlow logger behavior great again.
  logging.currentframe = _hack_the_main_frame
  handlers = [LogHandler(s) for s in streams]
  formatter = LogFormatter()
  for handler in handlers:
    handler.setFormatter(formatter)
  tensorflow_logger = logging.getLogger('tensorflow')
  tensorflow_logger.handlers = handlers
  werkzeug_logger = logging.getLogger('werkzeug')
  werkzeug_logger.setLevel(logging.WARNING)
  werkzeug_logger.handlers = handlers 
Example #6
Source File: loghelper.py    From moler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_caller(levels_to_go_up=0):
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.

    Based on findCaller() from logging module
    but allows to go higher back on stack

    :param levels_to_go_up: 0 - info about 'calling location' of caller of findCaller(); 1 - 'calling -1 location'
    :return:
    """
    f = logging.currentframe()
    # On some versions of IronPython, currentframe() returns None if
    # IronPython isn't run with -X:Frames.
    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
        for lv in range(levels_to_go_up):
            f = f.f_back
            if hasattr(f, "f_code"):
                co = f.f_code
            else:
                break

        rv = (co.co_filename, f.f_lineno, co.co_name)
        break
    return rv 
Example #7
Source File: logger.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def findCaller(self):
        f = logging.currentframe().f_back.f_back
        rv = "(unknown file)", 0, "(unknown function)"
        while hasattr(f, "f_code"):
            co = f.f_code
            filename = os.path.normcase(co.co_filename)
            if "logger" in filename:  # This line is modified.
                f = f.f_back
                continue
            filename = filename + " " + co.co_name
            rv = (filename, f.f_lineno, co.co_name)
            break
        return rv 
Example #8
Source File: utils.py    From py-SMART with GNU Lesser General Public License v2.1 5 votes vote down vote up
def findCaller(self, stack_info=False):
        """
        Overload built-in findCaller method
        to omit not only logging/__init__.py but also the current file
        """
        f = logging.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 = os.path.normcase(co.co_filename)
            if filename in (logging._srcfile, _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 
Example #9
Source File: test_interception.py    From loguru with MIT License 5 votes vote down vote up
def emit(self, record):
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # Find caller from where originated the logged message
        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) 
Example #10
Source File: logger.py    From pelisalacarta-ce with GNU General Public License v3.0 5 votes vote down vote up
def findCaller(self):
        f = logging.currentframe().f_back.f_back
        rv = "(unknown file)", 0, "(unknown function)"
        while hasattr(f, "f_code"):
            co = f.f_code
            filename = os.path.normcase(co.co_filename)
            if "logger" in filename: # This line is modified.
                f = f.f_back
                continue
            filename =filename + " " + co.co_name
            rv = (filename , f.f_lineno, co.co_name)
            break
        return rv 
Example #11
Source File: __init__.py    From abseil-py with Apache License 2.0 4 votes vote down vote up
def findCaller(self, stack_info=False, stacklevel=1):
    """Finds the frame of the calling method on the stack.

    This method skips any frames registered with the
    ABSLLogger and any methods from this file, and whatever
    method is currently being used to generate the prefix for the log
    line.  Then it returns the file name, line number, and method name
    of the calling method.  An optional fourth item may be returned,
    callers who only need things from the first three are advised to
    always slice or index the result rather than using direct unpacking
    assignment.

    Args:
      stack_info: bool, when True, include the stack trace as a fourth item
          returned.  On Python 3 there are always four items returned - the
          fourth will be None when this is False.  On Python 2 the stdlib
          base class API only returns three items.  We do the same when this
          new parameter is unspecified or False for compatibility.

    Returns:
      (filename, lineno, methodname[, sinfo]) of the calling method.
    """
    f_to_skip = ABSLLogger._frames_to_skip
    # Use sys._getframe(2) instead of logging.currentframe(), it's slightly
    # faster because there is one less frame to traverse.
    frame = sys._getframe(2)  # pylint: disable=protected-access

    while frame:
      code = frame.f_code
      if (_LOGGING_FILE_PREFIX not in code.co_filename and
          (code.co_filename, code.co_name,
           code.co_firstlineno) not in f_to_skip and
          (code.co_filename, code.co_name) not in f_to_skip):
        if six.PY2 and not stack_info:
          return (code.co_filename, frame.f_lineno, code.co_name)
        else:
          sinfo = None
          if stack_info:
            out = io.StringIO()
            out.write(u'Stack (most recent call last):\n')
            traceback.print_stack(frame, file=out)
            sinfo = out.getvalue().rstrip(u'\n')
          return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
      frame = frame.f_back