当前位置: 首页>>代码示例>>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;未经允许,请勿转载。