def find_caller_monkeypatch(self, stack_info=False):
    # pylint: disable=invalid-name, protected-access
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = logging.currentframe().f_back
    rv = "(unknown file)", 0, "(unknown function)"

    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)

        # This line is modified.
        if filename in (set_srcfile(), logging._srcfile):
            f = f.f_back
            continue

        # changes for 3.4
        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 = (filename, f.f_lineno, co.co_name, sinfo)
        break
    return rv
Exemple #2
0
 def findCaller(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 = 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 == logging._srcfile or co.co_name in ['log', 'info', 'warn', 'debug', 'error', 'ShowInfo']:
             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
        def findCaller():
            """
            Modified findCaller() that digs down in the frame stack until it
            finds the method that wrote to the stdout/stderr.
            """
            f = logging.currentframe()
            if f is not None:
                f = f.f_back
            rv = "(unknown file)", 0, "(unknown function)"

            if __file__[-4:].lower() in ['.pyc', '.pyo']:
                _thisfile = __file__[:-4] + '.py'
            else:
                _thisfile = __file__
            _thisfile = os.path.normcase(_thisfile)

            while hasattr(f, "f_code"):
                co = f.f_code
                filename = os.path.normcase(co.co_filename)
                if filename in (logging._srcfile, _thisfile):
                    f = f.f_back
                    continue
                rv = (co.co_filename, f.f_lineno, co.co_name)
                module = getmodule(f)
                if module:
                    logger.name = module.__name__
                break
            return rv
 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
Exemple #5
0
def _get_caller():
    """
    Returns information about the calling stack.

    The callstack must be exactly 3 deep for this to work. Typically
    this includes a logging function, :func:`AwareLogger._log` and
    this function.

    Returns:
        tuple: (module_name, filename, line_number, func_name)
    """
    caller_frame, module = None, None
    try:
        # Inspecting the call stack may seem expensive,
        # but this is more or less what the
        # logging module does already.
        caller_frame = logging.currentframe()
        caller_frame = caller_frame.f_back
        module = inspect.getmodule(caller_frame)
        co = caller_frame.f_code

        return (
            module.__name__ if module else None,
            co.co_filename,
            caller_frame.f_lineno,
            co.co_name
        )
    finally:
        # Prevent stack frames from causing memory leaks
        del caller_frame
        del module
Exemple #6
0
    def findCaller(self, stackwind=1):
        """
        Find the stack frame of the caller so that we can note the source
        file name, line number and function name.
        """
        # pylint: disable = W0221, C0103

        # + 2 = findCaller, _log
        f, idx = _logging.currentframe(), max(1, stackwind) + 2
        while idx:
            if f.f_back is None:
                break
            f = f.f_back
            idx -= 1
        rv = "(unknown file)", 0, "(unknown function)"
        while 1:
            co = getattr(f, "f_code", None)
            if co is None:
                break
            co = f.f_code
            filename = _os.path.normcase(co.co_filename)
            if filename == _logging._srcfile: # pylint: disable = W0212
                f = f.f_back
                continue
            rv = (filename, f.f_lineno, co.co_name)
            break
        return rv
Exemple #7
0
def current_call_stack(except_modules=[]):
    """ return the call hierarchy for the current stack """
    # we need the frame where logging was called not the frame of this call
    outer = inspect.getouterframes(logging.currentframe())
    notNone = [fr for fr in outer if inspect.getmodule(fr[0])]
    excepted = [fr for fr in notNone
                if inspect.getmodule(fr[0]).__name__ not in except_modules]
    return ["{module_name}.{func_name}:{lineno}".format(
        module_name=inspect.getmodule(fr).__name__,
        func_name=func_name, lineno=lineno)
            for fr, filename, lineno, func_name, lines, index in excepted]
 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
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #9
0
def find_log_caller_module(record):
    # type: (logging.LogRecord) -> Optional[str]
    '''Find the module name corresponding to where this record was logged.'''
    # 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()  # type: ignore  # Not in typeshed, and arguably shouldn't be
    while f is not None:
        if f.f_code.co_filename == record.pathname:
            return f.f_globals.get('__name__')
        f = f.f_back
    return None
Exemple #10
0
 def findCaller(self, stack_info=False):  # NOQA: N802
     f = logging.currentframe().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 filename in (__file__.replace('.pyc', '.py'),
                         defer.__file__.replace('.pyc', '.py')):
             f = f.f_back
             continue
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #11
0
 def findCaller(self):
     f = logging.currentframe().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 filename in (__file__.replace('.pyc', '.py'),
                         defer.__file__.replace('.pyc', '.py')):
             f = f.f_back
             continue
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #12
0
 def findCaller(self):
     f = logging.currentframe()
     if f is not None:
         f = f.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 filename == _srcfile:
             f = f.f_back
             continue
         rv = (co.co_filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #13
0
    def emit(self, record: Any) -> None:
        message = record.getMessage()
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        frame: Any = logging.currentframe()
        depth = 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        loguru.logger.opt(depth=depth,
                          exception=record.exc_info).log(level, message)
Exemple #14
0
 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
         if co.co_name == "<module>":
           rv = (filename , f.f_lineno, co.co_name)
         else:
           rv = (filename + " [" + co.co_name + "]" , f.f_lineno, co.co_name)
         break
     return rv
Exemple #15
0
 def findCaller(self):
     """Override findCaller method to consider this source file."""
     f = logging.currentframe()
     if f is not None:
         f = f.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 filename == logging._srcfile or filename == __file__:
             f = f.f_back
             continue
         rv = (co.co_filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #16
0
    def emit(self, record: logging.LogRecord) -> None:
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = str(record.levelno)

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = cast(FrameType, frame.f_back)
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level,
            record.getMessage(),
        )
Exemple #17
0
def findCaller(_):
    f = logging.currentframe()
    for _ in range(2 + logging._frame_delta):
        if f is not None:
            f = f.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 filename == logging._srcfile:
            f = f.f_back
            continue
        rv = (co.co_filename, f.f_lineno, co.co_name)
        break
    return rv
Exemple #18
0
 def findCaller(self, stack_info=False):  # NOQA: N802
     f = logging.currentframe().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 filename in (
             __file__.replace('.pyc', '.py'),
             defer.__file__.replace('.pyc', '.py'),
         ):
             f = f.f_back
             continue
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
    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())
Exemple #20
0
    def emit(self, record: logging.LogRecord) -> None:  # pragma: no cover
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = str(record.levelno)

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:  # noqa: WPS609
            frame = cast(FrameType, frame.f_back)
            depth += 1

        log = logger.bind(request_id='app')
        log.opt(depth=depth, exception=record.exc_info).log(
            level,
            record.getMessage(),
        )
Exemple #21
0
    def emit(self, record):
        try:
            level = logger.level(record.levelname).name
        except AttributeError:
            level = self.loglevel_mapping[record.levelno]

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename == logging.__file__:
            frame = frame.f_back
            depth += 1

        log = logger.bind(request_id='app')
        log.opt(
            depth=depth,
            exception=record.exc_info,
        ).log(level, record.getMessage())
Exemple #22
0
    def emit(self, record):
        # Get corresponding Loguru level if it exists
        try:
            level = logger.level(record.levelname).name
        except AttributeError:
            level = self.loglevel_mapping[record.levelno]

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

        log = logger.bind(request_id="app")
        log.opt(depth=depth,
                exception=record.exc_info).log(level, record.getMessage())
Exemple #23
0
    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(),
        )
Exemple #24
0
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 f is not None:
        if f.f_code.co_filename == record.pathname:
            return f.f_globals.get('__name__')
        f = f.f_back
    return None  # type: ignore # required because of previous ignore on f
Exemple #25
0
def current_call_stack(except_modules=[]):
    """ return the call hierarchy for the current stack """
    # we need the frame where logging was called not the frame of this call
    outer = inspect.getouterframes(logging.currentframe())
    notNone = [fr for fr in outer if inspect.getmodule(fr[0])]
    excepted = [
        fr for fr in notNone
        if inspect.getmodule(fr[0]).__name__ not in except_modules
    ]
    return [
        "{module_name}.{func_name}:{lineno}".format(
            module_name=inspect.getmodule(fr).__name__,
            func_name=func_name,
            lineno=lineno)
        for fr, filename, lineno, func_name, lines, index in excepted
    ]
Exemple #26
0
    def emit(self, record: logging.LogRecord) -> None:
        # Get corresponding Loguru level if it exists
        try:
            level = LOG.level(record.levelname).name
        except AttributeError:
            level = loglevel(record.levelno)

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

        LOG.opt(depth=depth,
                exception=record.exc_info).log(level, record.getMessage())
Exemple #27
0
    def emit(self, record: logging.LogRecord) -> None:
        # 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  # type: ignore
            depth += 1
        if record.name == "uvicorn.access":
            msg = InterceptHandler.accessFormat(record)
        else:
            msg = record.getMessage()
        logger.opt(depth=depth, exception=record.exc_info).log(level, msg)
Exemple #28
0
        def emit(self, record):
            """Intercept standard logging logs in loguru. Should test this for distributed pytorch lightning"""
            # 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())
Exemple #29
0
    def emit(self, record: logging.LogRecord) -> None:  # pragma: no cover
        try:
            level: str = logger.level(record.levelname).name
        except ValueError:
            level: str = self.loglevel_mapping[record.levelno]

        frame: 'Frame' = logging.currentframe()
        depth: int = 2

        while frame.f_code.co_filename == logging.__file__:  # noqa: WPS609
            frame = frame.f_back
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level,
            record.getMessage(),
        )
Exemple #30
0
def findCaller(self, stack_info=False):
    # type: (bool) -> Tuple
    """
    Find the stack frame of the caller so that we can note the source file
    name, line number and function name. Enhances the logging.findCaller().
    """

    frame = logging.currentframe()

    if frame is not None:
        frame = frame.f_back
    rv = "(unkown file)", 0, "(unknow function)"

    while hasattr(frame, "f_code"):
        co = frame.f_code
        filename = os.path.normcase(co.co_filename)
        # jump through local 'replace' func frame
        if  filename == logging._srcfile or \
            co.co_name == "replace":

            frame = frame.f_back
            continue

        if is_above_python_3_2():

            sinfo = None
            if stack_info:

                sio = io.StringIO()
                sio.write("Stack (most recent call last):\n")
                traceback.print_stack(frame, file=sio)
                sinfo = sio.getvalue()

                if sinfo[-1] == '\n':
                    sinfo = sinfo[:-1]

                sio.close()
            rv = (co.co_filename, frame.f_lineno, co.co_name, sinfo)

        else:
            rv = (co.co_filename, frame.f_lineno, co.co_name)

        break

    return rv
Exemple #31
0
 def findCaller(self, *args, **kwargs):  # NOQA: N802
     f = logging.currentframe().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 (
                 __file__.replace('.pyc', '.py'),
                 defer.__file__.replace('.pyc', '.py'),
         ):
             f = f.f_back
             continue
         rv = (co.co_filename, f.f_lineno, co.co_name, None)
         break
     if common.PY2:
         return rv[:-1]
     else:
         return rv
Exemple #32
0
        def emit(self, record):
            """Get corresponding Loguru level if it exists."""
            try:
                level = logger.level(record.levelname).name
            except (ValueError, AttributeError):  # pragma: no cover
                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(
                lazy=True,
                depth=depth,
                exception=record.exc_info,
            ).log(level, record.getMessage())
Exemple #33
0
 def filter(self, record):
     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
     while hasattr(f, "f_code"):
         co = f.f_code
         filename = os.path.normcase(co.co_filename)
         if filename != record.pathname:
             f = f.f_back
             continue
         try:
             record.xpath = f.f_locals['self'].get_xpath_relative()
         except AttributeError:
             record.xpath = ""
         break
     return True
Exemple #34
0
def find_caller_monkeypatch():
    # pylint: disable=invalid-name, protected-access
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    """
    f = logging.currentframe().f_back
    rv = "(unknown file)", 0, "(unknown function)"
    while hasattr(f, "f_code"):
        co = f.f_code
        filename = os.path.normcase(co.co_filename)
        # This line is modified.
        if filename in (set_srcfile(), logging._srcfile):
            f = f.f_back
            continue
        rv = (filename, f.f_lineno, co.co_name)
        break
    return rv
Exemple #35
0
    def findCaller(self, *args):
        """Override findCaller method to consider this source file."""

        from logging import currentframe, _srcfile

        f = currentframe()
        if f is not None:
            f = f.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 filename == _srcfile or filename == __file__:
                f = f.f_back
                continue
            rv = (co.co_filename, f.f_lineno, co.co_name)
            break
        return rv
Exemple #36
0
def create_tmpfs(module_name, size=None, multiplier=0.2, remove_old=True):
    if create_tmpfs.tmp_files_path:
        return create_tmpfs.tmp_files_path

    if size:
        assert_verbose(
            type(size) == str and (size.endswith('m') or size.endswith('g')),
            getframeinfo(logging.currentframe()),
            "bad formed size for tmpfs (try something like '500m' or '1g')")
    tmpfs_dir = create_tmpfs.tmpfs_dir

    def rmtree_handler(function, path, excinfo):
        try:
            os.remove(path)
        except OSError as remove_e:
            if remove_e.errno != errno.ENOENT:
                raise

    if not os.path.isdir(tmpfs_dir):
        os.mkdir(tmpfs_dir)
        if not size:  # by default allocate 20% or mem for tmpfs
            from psutil import virtual_memory
            size = int(virtual_memory().total * multiplier)
        logging.warning(
            "Creating TMPFS of size {}MB - you might need to provide a password"
            .format(size / 1024))
        subprocess.call([
            'sudo', 'mount', '-t', 'tmpfs', '-o', 'size={}'.format(size),
            'tmpfs', tmpfs_dir
        ])

    tmp_files_base_path = os.path.join(tmpfs_dir, getpass.getuser())
    if not os.path.isdir(tmp_files_base_path):
        os.mkdir(tmp_files_base_path)

    # make a subdir so that different modules won't collide
    tmp_files_path = os.path.join(tmp_files_base_path, module_name)
    if remove_old and os.path.isdir(tmp_files_path):
        shutil.rmtree(tmp_files_path, onerror=rmtree_handler)
    if not os.path.isdir(tmp_files_path):
        os.mkdir(tmp_files_path)

    create_tmpfs.tmp_files_path = tmp_files_path
    return tmp_files_path
Exemple #37
0
    def findCaller(self,
                   stack_info: bool = False,
                   stacklevel: int = 1) -> tuple:
        """Find the stack frame of the caller so that we can note the source
        file name, line number and function name.

        Args:
            stack_info (bool): TBD
            stacklevel (int): TBD

        Returns:
            tuple: filename, line number, module name, and stack trace
        """
        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
        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 in (logging._srcfile,
                            _srcfile):  # This is the only change
                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  # noqa R504
Exemple #38
0
def find_caller_name(is_func=False, steps=1):
    """
    用来发现调用这个方法的调用者的名字,类名或模块名
    :param is_func:
    :param steps:
    :return:
    """
    frame = logging.currentframe()
    for i in range(steps + 1):
        co = frame.f_code
        frame = frame.f_back

    if is_func:
        return co.co_name
    else:
        filename = os.path.basename(co.co_filename).split(".")[0]
        if filename == "__init__":
            filename = os.path.basename(os.path.dirname(co.co_filename))
        return filename
Exemple #39
0
    def _findCaller(self):
        '''
        获取调用者信息, 用于记录file func lineno
        '''

        f = logging.currentframe()

        if f is not None:
            f = f.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 filename == _srcfile:
                f = f.f_back
                continue
            rv = (co.co_filename, f.f_lineno, co.co_name)
            break
        return rv
Exemple #40
0
 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.
     """
     
     _frame_object = logging.currentframe()
     #On some versions of IronPython, currentframe() returns None if
     #IronPython isn't run with -X: Frames.
     if (_frame_object is not None):
         _frame_object = _frame_object.f_back
     
     rv = ("(unknown file)", 0, "(unknown function)", None)
     while hasattr(_frame_object, 'f_code'):
         _code_object = _frame_object.f_code
         filename = os.path.normcase(_code_object.co_filename)
         
         _next = _frame_object.f_back
         # noinspection PyProtectedMember,PyUnresolvedReferences
         if (filename == logging._srcfile):
             _frame_object = _next
             continue
         
         if (_next and hasattr(_next, 'f_code')):
             _parent_code = _next.f_code
             if (_parent_code.co_name == LOGGING_WRAPPER_NAME):
                 _frame_object = _next.f_back
                 continue
         
         _stack_info = None
         if (stack_info):
             _str_io = StringIO()
             _str_io.write('Stack (most recent call last):\n')
             traceback.print_stack(_frame_object, file=_str_io)
             _stack_info = _str_io.getvalue()
             if (_stack_info[-1] == '\n'):
                 _stack_info = _stack_info[:-1]
             _str_io.close()
         
         rv = (_code_object.co_filename, _frame_object.f_lineno, _code_object.co_name, _stack_info)
         break
     return rv
Exemple #41
0
    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 = 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
        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 == 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()

            localvars = f.f_locals
            classname_prefix = ""
            if "self" in localvars:
                classname_prefix = localvars["self"].__class__.__name__ + "::"

            rv = (co.co_filename, f.f_lineno, classname_prefix + co.co_name,
                  sinfo)
            break
        return rv
    def emit(self, record: logging.LogRecord) -> None:
        """Propagates logs to loguru.

        :param record: record to log.
        """
        try:
            level: Union[str, int] = 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  # type: ignore
            depth += 1

        logger.opt(depth=depth, exception=record.exc_info).log(
            level,
            record.getMessage(),
        )
Exemple #43
0
 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 = 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.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 filename == logging._srcfile:
             f = f.f_back.f_back
             continue
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
Exemple #44
0
 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 = 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.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 filename == logging._srcfile:
             f = f.f_back.f_back
             continue
         rv = (filename, f.f_lineno, co.co_name)
         break
     return rv
    def _findCaller(self):
        """
        Cut down copy of Python 3.6.6's logging.Logger.findCaller()

        Find the stack frame of the caller so that we can note the source
        file name, line number and function name.
        """
        f = logging.currentframe()
        if f is not None:
            f = f.f_back
        while hasattr(f, "f_code"):
            co = f.f_code
            try:
                # do this in a try block to protect ourselves from faulty is_interesting_frame implementations
                is_interesting_frame = self.is_interesting_frame(f)
            except:  # noqa
                is_interesting_frame = False
            if is_interesting_frame:
                return co.co_filename, f.f_lineno, co.co_name
            f = f.f_back
        return None, None, None
    def findCaller(self):
        f = logging.currentframe()

        if f is not None:
            f = f.f_back

        rv = "(unknown file)", 0, "(unknown function)"

        while hasattr(f, "f_code"):
            co = f.f_code
            path = self.normalize_path(co.co_filename)

            if not self.valid(path):
                # Ignore sandbox frame
                f = f.f_back
                continue

            rv = (co.co_filename, f.f_lineno, co.co_name)
            break

        return rv
Exemple #47
0
def _findCaller(self):
    u"""
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    返回被调用的 文件名、行号、函数名
    """
    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 == _srcfile:
            if filename in (_srcfile, logging._srcfile):
                f = f.f_back
                continue
            rv = (filename, f.f_lineno, co.co_name)
            break
    except:  # 多线程高并发时,会报错,这里捕获一下以免抛出去
        pass
    return rv
Exemple #48
0
def find_caller():
    """
    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
Exemple #49
0
 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 = 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
   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 in [logging._srcfile, self._my_srcfile] \
        or filename.startswith(self._structlog_dir):
       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
Exemple #50
0
 def cf():
     return logging.currentframe()