Python traceback.format_stack() Examples

The following are 30 code examples of traceback.format_stack(). 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 traceback , or try the search function .
Example #1
Source File: output.py    From stem with GNU Lesser General Public License v3.0 7 votes vote down vote up
def thread_stacktraces():
  """
  Provides a dump of the stacktrace information for all active threads.

  :returns: **dict** that maps thread names to their stacktrace
  """

  stacktraces = {}

  for thread in threading.enumerate():
    frame = sys._current_frames().get(thread.ident, None)

    if frame:
      stacktraces[thread.name] = ''.join(traceback.format_stack(frame))
    else:
      stacktraces[thread.name] = 'No traceback available'

  return stacktraces 
Example #2
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def log(msg, msgx='', level=logging.INFO, need_tb=False):
    """
    Logging in UCC Config Module.
    :param msg: message content
    :param msgx: detail info.
    :param level: logging level
    :param need_tb: if need logging traceback
    :return:
    """
    global LOGGING_STOPPED
    if LOGGING_STOPPED:
        return

    msgx = ' - ' + msgx if msgx else ''
    content = 'UCC Config Module: %s%s' % (msg, msgx)
    if need_tb:
        stack = ''.join(traceback.format_stack())
        content = '%s\r\n%s' % (content, stack)
    stulog.logger.log(level, content, exc_info=1) 
Example #3
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def log(msg, msgx='', level=logging.INFO, need_tb=False):
    """
    Logging in UCC Config Module.
    :param msg: message content
    :param msgx: detail info.
    :param level: logging level
    :param need_tb: if need logging traceback
    :return:
    """
    global LOGGING_STOPPED
    if LOGGING_STOPPED:
        return

    msgx = ' - ' + msgx if msgx else ''
    content = 'UCC Config Module: %s%s' % (msg, msgx)
    if need_tb:
        stack = ''.join(traceback.format_stack())
        content = '%s\r\n%s' % (content, stack)
    stulog.logger.log(level, content, exc_info=1) 
Example #4
Source File: message.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def error(message: str, *, stack: str = None, replace: bool = False) -> None:
    """Display an error message.

    Args:
        message: The message to show.
        stack: The stack trace to show (if any).
        replace: Replace existing messages which are still being shown.
    """
    if stack is None:
        stack = ''.join(traceback.format_stack())
        typ = 'error'
    else:
        typ = 'error (from exception)'
    _log_stack(typ, stack)
    log.message.error(message)
    global_bridge.show(usertypes.MessageLevel.error, message, replace) 
Example #5
Source File: pool.py    From jbox with MIT License 6 votes vote down vote up
def _do_get(self):
        if self._checked_out:
            if self._checkout_traceback:
                suffix = ' at:\n%s' % ''.join(
                    chop_traceback(self._checkout_traceback))
            else:
                suffix = ''
            raise AssertionError("connection is already checked out" + suffix)

        if not self._conn:
            self._conn = self._create_connection()

        self._checked_out = True
        if self._store_traceback:
            self._checkout_traceback = traceback.format_stack()
        return self._conn 
Example #6
Source File: mutex.py    From tf-pose with Apache License 2.0 6 votes vote down vote up
def tryLock(self, timeout=None, id=None):
        if timeout is None:
            locked = QtCore.QMutex.tryLock(self)
        else:
            locked = QtCore.QMutex.tryLock(self, timeout)

        if self.debug and locked:
            self.l.lock()
            try:
                if id is None:
                    self.tb.append(''.join(traceback.format_stack()[:-1]))
                else:
                    self.tb.append("  " + str(id))
                #print 'trylock', self, len(self.tb)
            finally:
                self.l.unlock()
        return locked 
Example #7
Source File: defer.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _startRunCallbacks(self, result):
        if self.called:
            if self._suppressAlreadyCalled:
                self._suppressAlreadyCalled = False
                return
            if self.debug:
                if self._debugInfo is None:
                    self._debugInfo = DebugInfo()
                extra = "\n" + self._debugInfo._getDebugTracebacks()
                raise AlreadyCalledError(extra)
            raise AlreadyCalledError
        if self.debug:
            if self._debugInfo is None:
                self._debugInfo = DebugInfo()
            self._debugInfo.invoker = traceback.format_stack()[:-2]
        self.called = True
        self.result = result
        self._runCallbacks() 
Example #8
Source File: help_functions.py    From pylane with GNU General Public License v3.0 6 votes vote down vote up
def inspect_threads(thread_names=[]):
    """inspect_threads() -> {thread_name: {"locals": {}, "stack": ""}} : return threads' locals and stack"""
    import threading
    import sys
    import traceback
    pylane_thread_name = "pylane-shell-thread"
    stacks = {}
    frames = sys._current_frames()
    threads = threading.enumerate()
    for thread in threads:
        if thread.name == pylane_thread_name:
            continue
        if thread_names and thread.name not in thread_names:
            continue
        frame = frames.get(thread.ident)
        stack = ''.join(traceback.format_stack(frame)) if frame else ''
        stacks[thread.name] = {
            "locals": frame.f_locals,
            "stack": stack
        }
    return stacks 
Example #9
Source File: __init__.py    From universe with MIT License 6 votes vote down vote up
def format_error(e):
    # errback automatically wraps everything in a Twisted Failure
    if isinstance(e, failure.Failure):
        e = e.value

    if isinstance(e, str):
        err_string = e
    elif six.PY2:
        err_string = traceback.format_exc(e).rstrip()
    else:
        err_string = ''.join(traceback.format_exception(type(e), e, e.__traceback__)).rstrip()

    if err_string == 'None':
        # Reasonable heuristic for exceptions that were created by hand
        last = traceback.format_stack()[-2]
        err_string = '{}\n  {}'.format(e, last)
    # Quick and dirty hack for now.
    err_string = err_string.replace('Connection to the other side was lost in a non-clean fashion', 'Connection to the other side was lost in a non-clean fashion (HINT: this generally actually means we got a connection refused error. Check that the remote is actually running.)')
    return error.Error(err_string) 
Example #10
Source File: report.py    From iopipe-python with Apache License 2.0 6 votes vote down vote up
def retain_error(self, error, frame=None):
        """
        Adds details of an error to the report.

        :param error: The error exception to add to the report.
        """
        if frame is None:
            stack = traceback.format_exc()
            self.labels.add("@iopipe/error")
        else:
            stack = "\n".join(traceback.format_stack(frame))
            self.labels.add("@iopipe/timeout")
        details = {
            "name": type(error).__name__,
            "message": "{}".format(error),
            "stack": stack,
        }
        self.report["errors"] = details 
Example #11
Source File: rtp_cluster.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def debug_signal(signum, frame):
    import sys, traceback
    for thread_id, stack in sys._current_frames().iteritems():
        print('Thread id: %s\n%s' % (thread_id, ''.join(traceback.format_stack(stack)))) 
Example #12
Source File: mpi.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def _assert(condition):
    if not condition:
        sys.stderr.write(''.join(traceback.format_stack()[:-1]))
        comm.Abort() 
Example #13
Source File: rift_expect_session.py    From rift-python with Apache License 2.0 5 votes vote down vote up
def log_expect_failure(self, expected_pattern):
        self.write_result("\n\n*** Did not find expected pattern {}\n\n".format(expected_pattern))
        # Generate a call stack in rift_expect.log for easier debugging
        # But pytest call stacks are very deep, so only show the "interesting" lines
        for line in traceback.format_stack():
            if "tests/" in line:
                self.write_result(line.strip())
                self.write_result("\n") 
Example #14
Source File: log_expect_session.py    From rift-python with Apache License 2.0 5 votes vote down vote up
def expect_failure(self, msg):
        self._results_file.write(msg + "\n\n")
        # Generate a call stack in rift_expect.log for easier debugging
        # But pytest call stacks are very deep, so only show the "interesting" lines
        for line in traceback.format_stack():
            if "tests/" in line:
                self._results_file.write(line.strip())
                self._results_file.write("\n")
        assert False, msg + " (see log_expect.log for details)" 
Example #15
Source File: config_generator.py    From rift-python with Apache License 2.0 5 votes vote down vote up
def log_expect_failure(self):
        self.write_result("\n\n*** Did not find expected pattern\n\n")
        # Generate a call stack in the log file for easier debugging
        for line in traceback.format_stack():
            self.write_result(line.strip())
            self.write_result("\n") 
Example #16
Source File: ioloop.py    From tornado-zh with MIT License 5 votes vote down vote up
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame))) 
Example #17
Source File: ioloop.py    From tornado-zh with MIT License 5 votes vote down vote up
def log_stack(self, signal, frame):
        """Signal handler to log the stack trace of the current thread.

        For use with `set_blocking_signal_threshold`.
        """
        gen_log.warning('IOLoop blocked for %f seconds in\n%s',
                        self._blocking_signal_threshold,
                        ''.join(traceback.format_stack(frame))) 
Example #18
Source File: utils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def yaml_load(f: typing.Union[str, typing.IO[str]]) -> typing.Any:
    """Wrapper over yaml.load using the C loader if possible."""
    start = datetime.datetime.now()

    # WORKAROUND for https://github.com/yaml/pyyaml/pull/181
    with log.ignore_py_warnings(
            category=DeprecationWarning,
            message=r"Using or importing the ABCs from 'collections' instead "
            r"of from 'collections\.abc' is deprecated.*"):
        data = yaml.load(f, Loader=YamlLoader)

    end = datetime.datetime.now()

    delta = (end - start).total_seconds()
    deadline = 10 if 'CI' in os.environ else 2
    if delta > deadline:  # pragma: no cover
        log.misc.warning(
            "YAML load took unusually long, please report this at "
            "https://github.com/qutebrowser/qutebrowser/issues/2777\n"
            "duration: {}s\n"
            "PyYAML version: {}\n"
            "C extension: {}\n"
            "Stack:\n\n"
            "{}".format(
                delta, yaml.__version__, YAML_C_EXT,
                ''.join(traceback.format_stack())))

    return data 
Example #19
Source File: message.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def warning(message: str, *, replace: bool = False) -> None:
    """Display a warning message.

    Args:
        message: The message to show.
        replace: Replace existing messages which are still being shown.
    """
    _log_stack('warning', ''.join(traceback.format_stack()))
    log.message.warning(message)
    global_bridge.show(usertypes.MessageLevel.warning, message, replace) 
Example #20
Source File: gateway.py    From discord.py with MIT License 5 votes vote down vote up
def run(self):
        while not self._stop_ev.wait(self.interval):
            if self._last_ack + self.heartbeat_timeout < time.perf_counter():
                log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id)
                coro = self.ws.close(4000)
                f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)

                try:
                    f.result()
                except Exception:
                    pass
                finally:
                    self.stop()
                    return

            data = self.get_payload()
            log.debug(self.msg, data['d'])
            coro = self.ws.send_as_json(data)
            f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
            try:
                # block until sending is complete
                total = 0
                while True:
                    try:
                        f.result(10)
                        break
                    except concurrent.futures.TimeoutError:
                        total += 10
                        try:
                            frame = sys._current_frames()[self._main_thread_id]
                        except KeyError:
                            msg = self.block_msg
                        else:
                            stack = traceback.format_stack(frame)
                            msg = '%s\nLoop thread traceback (most recent call last):\n%s' % (self.block_msg, ''.join(stack))
                        log.warning(msg, total)

            except Exception:
                self.stop()
            else:
                self._last_send = time.perf_counter() 
Example #21
Source File: utils.py    From IPProxyTool with MIT License 5 votes vote down vote up
def log(msg, level = logging.DEBUG):
    logging.log(level, msg)
    print('%s [%s], msg:%s' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), level, msg))

    if level == logging.WARNING or level == logging.ERROR:
        for line in traceback.format_stack():
            print(line.strip())

        for line in traceback.format_stack():
            logging.log(level, line.strip())


# 服务器使用,清理端口占用 
Example #22
Source File: misc.py    From codimension with GNU General Public License v3.0 5 votes vote down vote up
def printStack():
    """Prints the stack in the log window"""
    for line in traceback.format_stack():
        print(line.strip()) 
Example #23
Source File: logging.py    From waveglow with Apache License 2.0 5 votes vote down vote up
def _logger_find_caller(stack_info=False):  # pylint: disable=g-wrong-blank-lines
        code, frame = _get_caller(4)
        sinfo = None
        if stack_info:
            sinfo = '\n'.join(_traceback.format_stack())
        if code:
            return (code.co_filename, frame.f_lineno, code.co_name, sinfo)
        else:
            return '(unknown file)', 0, '(unknown function)', sinfo 
Example #24
Source File: utils.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def GetStack():
    """Returns the current call stack as a string."""
    return "".join(traceback.format_stack()) 
Example #25
Source File: obj.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, reason="None Object", *args, **kwargs):
        # Often None objects are instantiated on purpose so its not really that
        # important to see their reason.
        if kwargs.get("log"):
            logging.log(logging.WARN, reason)
        self.reason = utils.SmartUnicode(reason)
        self.strict = kwargs.get("strict")
        self.args = args
        if self.strict:
            self.bt = ''.join(traceback.format_stack()[:-2]) 
Example #26
Source File: debug.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def backtrace(skip=0):
    return ''.join(traceback.format_stack()[:-(skip+1)]) 
Example #27
Source File: debug.py    From tf-pose with Apache License 2.0 5 votes vote down vote up
def formatException(exctype, value, tb, skip=0):
    """Return a list of formatted exception strings.
    
    Similar to traceback.format_exception, but displays the entire stack trace
    rather than just the portion downstream of the point where the exception is
    caught. In particular, unhandled exceptions that occur during Qt signal
    handling do not usually show the portion of the stack that emitted the
    signal.
    """
    lines = traceback.format_exception(exctype, value, tb)
    lines = [lines[0]] + traceback.format_stack()[:-(skip+1)] + ['  --- exception caught here ---\n'] + lines[1:]
    return lines 
Example #28
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def debug_every_sec(cls, msg, duration):
        stack_list = traceback.format_stack()
        if len(stack_list) <= 1:
            Logger.debug(msg)
            return
        key = stack_list[-2]

        if (
            key not in cls._last_debug_time_map
            or time.time() - cls._last_debug_time_map[key] > duration
        ):
            Logger.debug(msg)
            cls._last_debug_time_map[key] = time.time() 
Example #29
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def info_every_sec(cls, msg, duration):
        stack_list = traceback.format_stack()
        if len(stack_list) <= 1:
            Logger.info(msg)
            return
        key = stack_list[-2]

        if (
            key not in cls._last_info_time_map
            or time.time() - cls._last_info_time_map[key] > duration
        ):
            Logger.info(msg)
            cls._last_info_time_map[key] = time.time() 
Example #30
Source File: utils.py    From pyquarkchain with MIT License 5 votes vote down vote up
def warning_every_sec(cls, msg, duration):
        stack_list = traceback.format_stack()
        if len(stack_list) <= 1:
            Logger.warning(msg)
            return
        key = stack_list[-2]

        if (
            key not in cls._last_warning_time_map
            or time.time() - cls._last_warning_time_map[key] > duration
        ):
            Logger.warning(msg)
            cls._last_warning_time_map[key] = time.time()