當前位置: 首頁>>代碼示例>>Python>>正文


Python logger.exception方法代碼示例

本文整理匯總了Python中loguru.logger.exception方法的典型用法代碼示例。如果您正苦於以下問題:Python logger.exception方法的具體用法?Python logger.exception怎麽用?Python logger.exception使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在loguru.logger的用法示例。


在下文中一共展示了logger.exception方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: resume

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def resume(self, downloads: List[Download]) -> List[bool]:
        """
        Resume (unpause) the given downloads.

        Parameters:
            downloads: the list of downloads to resume.

        Returns:
            Success or failure of the operation for each given download.
        """
        # TODO: batch/multicall candidate
        result = []

        for download in downloads:
            try:
                self.client.unpause(download.gid)
            except ClientException as error:
                logger.debug(f"Failed to resume download {download.gid}")
                logger.opt(exception=True).trace(error)
                result.append(error)
            else:
                result.append(True)

        return result 
開發者ID:pawamoy,項目名稱:aria2p,代碼行數:26,代碼來源:api.py

示例2: main

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def main() -> None:
    parser = get_argument_parser()
    arguments = parser.parse_args()
    logger.stop(0)
    logger.add(sys.stderr, level=arguments.logging_level)

    # noinspection PyBroadException
    try:
        cli_main(arguments)
    except KeyboardInterrupt:
        logger.info("Aborted")
    except ConfigError as error:
        logger.error("Invalid configuration: {}", error)
    except MissingDependencyError as error:
        logger.error("Missing dependency: {}", error)
    except Exception:
        logger.exception("Unexpected error occurred:") 
開發者ID:cryzed,項目名稱:TrafficToll,代碼行數:19,代碼來源:__main__.py

示例3: test_exception

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception(make_logging_logger, capsys, use_opt):
    make_logging_logger("tests", StreamHandler(sys.stderr))
    logger.add(PropagateHandler(), format="{message}")

    try:
        1 / 0
    except:
        if use_opt:
            logger.opt(exception=True).error("Oops...")
        else:
            logger.exception("Oops...")

    out, err = capsys.readouterr()
    lines = err.strip().splitlines()

    error = "ZeroDivisionError: division by zero"

    assert out == ""
    assert lines[0] == "Oops..."
    assert lines[-1] == error
    assert err.count(error) == 1 
開發者ID:Delgan,項目名稱:loguru,代碼行數:23,代碼來源:test_propagation.py

示例4: test_enqueue_with_exception

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_enqueue_with_exception():
    x = []

    def sink(message):
        time.sleep(0.1)
        x.append(message)

    logger.add(sink, format="{message}", enqueue=True)

    try:
        1 / 0
    except ZeroDivisionError:
        logger.exception("Error")

    assert len(x) == 0
    time.sleep(0.2)
    assert len(x) == 1
    lines = x[0].splitlines()

    assert lines[0] == "Error"
    assert lines[-1] == "ZeroDivisionError: division by zero" 
開發者ID:Delgan,項目名稱:loguru,代碼行數:23,代碼來源:test_add_option_enqueue.py

示例5: test_no_exception

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_no_exception():
    result = None

    class NoExceptionHandler(Handler):
        def emit(self, record):
            nonlocal result
            result = bool(not record.exc_info)

    logger.add(NoExceptionHandler())

    try:
        1 / 0
    except ZeroDivisionError:
        logger.exception("Error")

    assert result is False 
開發者ID:Delgan,項目名稱:loguru,代碼行數:18,代碼來源:test_standard_handler.py

示例6: test_exception

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception(capsys):
    result = None

    class ExceptionHandler(Handler):
        def emit(self, record):
            nonlocal result
            result = bool(record.exc_info)

    logger.add(ExceptionHandler())

    try:
        1 / 0
    except ZeroDivisionError:
        logger.exception("Error")

    assert result is True 
開發者ID:Delgan,項目名稱:loguru,代碼行數:18,代碼來源:test_standard_handler.py

示例7: test_exception_formatting

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_exception_formatting(tmpdir):
    file = tmpdir.join("test.log")
    logger.add(FileHandler(str(file)), format="{message}")

    try:
        1 / 0
    except ZeroDivisionError:
        logger.exception("Error")

    result = file.read()
    lines = result.strip().splitlines()

    error = "ZeroDivisionError: division by zero"

    assert lines[1].startswith("Traceback")
    assert lines[-1] == error
    assert result.count(error) == 1 
開發者ID:Delgan,項目名稱:loguru,代碼行數:19,代碼來源:test_standard_handler.py

示例8: test_diagnose

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_diagnose(writer):
    logger.add(writer, format="{message}", diagnose=True)
    try:
        1 / 0
    except:
        logger.exception("")
    result_with = writer.read().strip()

    logger.remove()
    writer.clear()

    logger.add(writer, format="{message}", diagnose=False)
    try:
        1 / 0
    except:
        logger.exception("")
    result_without = writer.read().strip()

    assert len(result_with.splitlines()) > len(result_without.splitlines()) 
開發者ID:Delgan,項目名稱:loguru,代碼行數:21,代碼來源:test_add_option_diagnose.py

示例9: test_sink_encoding

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_sink_encoding(writer, encoding):
    class Writer:
        def __init__(self, encoding):
            self.encoding = encoding
            self.output = ""

        def write(self, message):
            self.output += message

    writer = Writer(encoding)
    logger.add(writer, backtrace=True, diagnose=True, colorize=False, format="", catch=False)

    def foo(a, b):
        a / b

    def bar(c):
        foo(c, 0)

    try:
        bar(4)
    except ZeroDivisionError:
        logger.exception("")

    assert writer.output.endswith("ZeroDivisionError: division by zero\n") 
開發者ID:Delgan,項目名稱:loguru,代碼行數:26,代碼來源:test_catch_exceptions.py

示例10: test_onerror

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def test_onerror(writer):
    is_error_valid = False
    logger.add(writer, format="{message}")

    def onerror(error):
        nonlocal is_error_valid
        logger.info("Called after logged message")
        _, exception, _ = sys.exc_info()
        is_error_valid = (error == exception) and isinstance(error, ZeroDivisionError)

    @logger.catch(onerror=onerror)
    def a():
        1 / 0

    a()

    assert is_error_valid
    assert writer.read().endswith(
        "ZeroDivisionError: division by zero\n" "Called after logged message\n"
    ) 
開發者ID:Delgan,項目名稱:loguru,代碼行數:22,代碼來源:test_catch_exceptions.py

示例11: _render

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def _render(self, element: AbstractElement) -> LayoutUpdate:
        # current element ids
        current: Set[str] = set(self._element_state)

        # all element updates
        new: Dict[str, Dict[str, Any]] = {}

        parent = self._element_parent(element)
        render_error: Optional[Exception] = None
        try:
            async for element_id, model in self._render_element(element, parent):
                new[element_id] = model
        except asyncio.CancelledError:
            raise  # we don't want to supress cancellations
        except Exception as error:
            logger.exception(f"Failed to render {element}")
            render_error = error
        finally:
            # all deleted element ids
            old: List[str] = list(current.difference(self._element_state))
            update = LayoutUpdate(element.id, new, old, render_error)

        # render bundle
        return update 
開發者ID:rmorshea,項目名稱:idom,代碼行數:26,代碼來源:layout.py

示例12: run_once

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def run_once(self):
        """Run each source once, passing artifacts to each operator."""
        # Track some statistics about artifacts in a summary object.
        summary = collections.Counter()

        for source in self.sources:
            # Run the source to collect artifacts.
            logger.debug(f"Running source '{source}'")
            try:
                with self.statsd.timer(f'source.{source}'):
                    saved_state, artifacts = self.sources[source].run(self.statedb.get_state(source))

            except Exception:
                self.statsd.incr(f'error.source.{source}')
                logger.exception(f"Unknown error in source '{source}'")
                continue

            # Save the source state.
            self.statedb.save_state(source, saved_state)

            # Process artifacts with each operator.
            for operator in self.operators:
                logger.debug(f"Processing {len(artifacts)} artifacts from source '{source}' with operator '{operator}'")
                try:
                    with self.statsd.timer(f'operator.{operator}'):
                        self.operators[operator].process(artifacts)

                except Exception:
                    self.statsd.incr(f'error.operator.{operator}')
                    logger.exception(f"Unknown error in operator '{operator}'")
                    continue

            # Record stats and update the summary.
            types = artifact_types(artifacts)
            summary.update(types)
            for artifact_type in types:
                self.statsd.incr(f'source.{source}.{artifact_type}', types[artifact_type])
                self.statsd.incr(f'artifacts.{artifact_type}', types[artifact_type])

        # Log the summary.
        logger.log('NOTIFY', f"New artifacts: {dict(summary)}") 
開發者ID:InQuest,項目名稱:ThreatIngestor,代碼行數:43,代碼來源:__init__.py

示例13: __make_request_method

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def __make_request_method(self, teststep_dict, entry_json):
        """ parse HAR entry request method, and make teststep method.
        """
        method = entry_json["request"].get("method")
        if not method:
            logger.exception("method missed in request.")
            sys.exit(1)

        teststep_dict["request"]["method"] = method 
開發者ID:httprunner,項目名稱:httprunner,代碼行數:11,代碼來源:core.py

示例14: superuser

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def superuser(user_id: int, remove: bool):
    from app.utils.executor import runner
    from app.utils.superuser import create_super_user

    try:
        result = runner.start(create_super_user(user_id, remove))
    except Exception as e:
        logger.exception("Failed to create superuser: {e}", e=e)
        result = None

    if not result:
        exit(1) 
開發者ID:aiogram,項目名稱:bot,代碼行數:14,代碼來源:cli.py

示例15: errors_handler

# 需要導入模塊: from loguru import logger [as 別名]
# 或者: from loguru.logger import exception [as 別名]
def errors_handler(update: types.Update, exception: Exception):
    try:
        raise exception
    except Exception as e:
        logger.exception("Cause exception {e} in update {update}", e=e, update=update)
    return True 
開發者ID:aiogram,項目名稱:bot,代碼行數:8,代碼來源:base.py


注:本文中的loguru.logger.exception方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。