Python loguru.logger.exception() Examples

The following are 30 code examples of loguru.logger.exception(). 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 loguru.logger , or try the search function .
Example #1
Source File: test_standard_handler.py    From loguru with MIT License 6 votes vote down vote up
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 
Example #2
Source File: test_catch_exceptions.py    From loguru with MIT License 6 votes vote down vote up
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") 
Example #3
Source File: test_propagation.py    From loguru with MIT License 6 votes vote down vote up
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 
Example #4
Source File: api.py    From aria2p with ISC License 6 votes vote down vote up
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 
Example #5
Source File: test_add_option_diagnose.py    From loguru with MIT License 6 votes vote down vote up
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()) 
Example #6
Source File: __main__.py    From TrafficToll with GNU General Public License v3.0 6 votes vote down vote up
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:") 
Example #7
Source File: test_add_option_enqueue.py    From loguru with MIT License 6 votes vote down vote up
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" 
Example #8
Source File: test_standard_handler.py    From loguru with MIT License 6 votes vote down vote up
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 
Example #9
Source File: test_standard_handler.py    From loguru with MIT License 6 votes vote down vote up
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 
Example #10
Source File: test_catch_exceptions.py    From loguru with MIT License 6 votes vote down vote up
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"
    ) 
Example #11
Source File: layout.py    From idom with MIT License 6 votes vote down vote up
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 
Example #12
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def normalize(exception):
    """Normalize exception output for reproducible test cases"""
    if os.name:
        exception = re.sub(
            r'File[^"]+"[^"]+\.py[^"]*"', lambda m: m.group().replace("\\", "/"), exception
        )
        exception = re.sub(r"(\r\n|\r|\n)", "\n", exception)

    exception = re.sub(
        r'"[^"]*/somelib/__init__.py"', '"/usr/lib/python/somelib/__init__.py"', exception
    )

    exception = re.sub(r"\b0x[0-9a-fA-F]+\b", "0xDEADBEEF", exception)

    if platform.python_implementation() == "PyPy":
        exception = (
            exception.replace(
                "<function str.isdigit at 0xDEADBEEF>", "<method 'isdigit' of 'str' objects>"
            )
            .replace(
                "<function coroutine.send at 0xDEADBEEF>", "<method 'send' of 'coroutine' objects>"
            )
            .replace(
                "<function NoneType.__bool__ at 0xDEADBEEF>",
                "<slot wrapper '__bool__' of 'NoneType' objects>",
            )
        )

    return exception 
Example #13
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_sysconfig_get_path_return_none(writer, monkeypatch):
    monkeypatch.setattr(sysconfig, "get_path", lambda *a, **k: None)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #14
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_file_sink_ascii_encoding(tmpdir):
    file = tmpdir.join("test.log")
    logger.add(str(file), format="", encoding="ascii", errors="backslashreplace", catch=False)
    a = "天"

    try:
        "天" * a
    except Exception:
        logger.exception("")

    logger.remove()
    result = file.read_text("ascii")
    assert result.count('"\\u5929" * a') == 1
    assert result.count("-> '\\u5929'") == 1 
Example #15
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_file_sink_utf8_encoding(tmpdir):
    file = tmpdir.join("test.log")
    logger.add(str(file), format="", encoding="utf8", errors="strict", catch=False)
    a = "天"

    try:
        "天" * a
    except Exception:
        logger.exception("")

    logger.remove()
    result = file.read_text("utf8")
    assert result.count('"天" * a') == 1
    assert result.count("└ '天'") == 1 
Example #16
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_has_sys_real_prefix(writer, monkeypatch):
    monkeypatch.setattr(sys, "real_prefix", "/foo/bar/baz", raising=False)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #17
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_no_sys_real_prefix(writer, monkeypatch):
    monkeypatch.delattr(sys, "real_prefix", raising=False)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #18
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_no_site_getsitepackages(writer, monkeypatch):
    monkeypatch.delattr(site, "getsitepackages", raising=False)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #19
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_user_site_is_path(writer, monkeypatch):
    monkeypatch.setattr(site, "USER_SITE", "/foo/bar/baz")
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #20
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_user_site_is_none(writer, monkeypatch):
    monkeypatch.setattr(site, "USER_SITE", None)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #21
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_sysconfig_get_path_return_path(writer, monkeypatch):
    monkeypatch.setattr(sysconfig, "get_path", lambda *a, **k: "/foo/bar/baz")
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #22
Source File: test_add_option_serialize.py    From loguru with MIT License 5 votes vote down vote up
def test_serialize_with_exception():
    sink = JsonSink()
    logger.add(sink, format="{message}", serialize=True)

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

    lines = sink.json["text"].splitlines()
    assert lines[0] == "Error"
    assert lines[-1] == "ZeroDivisionError: division by zero"
    assert bool(sink.json["record"]["exception"]) 
Example #23
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_distutils_get_python_lib_raise_exception(writer, monkeypatch):
    def raising(*a, **k):
        raise distutils.sysconfig.DistutilsPlatformError()

    monkeypatch.setattr(distutils.sysconfig, "get_python_lib", raising)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #24
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_distutils_not_installed(writer, monkeypatch):
    monkeypatch.setitem(sys.modules, "distutils", None)
    monkeypatch.setitem(sys.modules, "distutils.errors", None)
    monkeypatch.setitem(sys.modules, "distutils.sysconfig", None)
    monkeypatch.delattr(loguru._better_exceptions, "distutils", raising=False)
    monkeypatch.delattr(loguru._better_exceptions, "distutils.errors", raising=False)
    monkeypatch.delattr(loguru._better_exceptions, "distutils.syconfig", raising=False)
    logger.add(writer, backtrace=False, diagnose=True, colorize=False, format="")

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

    assert writer.read().endswith("ZeroDivisionError: division by zero\n") 
Example #25
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_no_exception(writer):
    logger.add(writer, backtrace=False, diagnose=False, colorize=False, format="{message}")

    logger.exception("No Error.")

    assert writer.read() in (
        "No Error.\nNoneType\n",
        "No Error.\nNoneType: None\n",  # Old versions of Python 3.5
    ) 
Example #26
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_exception_is_none():
    err = object()

    def writer(msg):
        nonlocal err
        err = msg.record["exception"]

    logger.add(writer)

    logger.error("No exception")

    assert err is None 
Example #27
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_exception_is_tuple():
    exception = None

    def writer(msg):
        nonlocal exception
        exception = msg.record["exception"]

    logger.add(writer, catch=False)

    try:
        1 / 0
    except ZeroDivisionError:
        logger.exception("Exception")
        reference = sys.exc_info()

    t_1, v_1, tb_1 = exception
    t_2, v_2, tb_2 = (x for x in exception)
    t_3, v_3, tb_3 = exception[0], exception[1], exception[2]
    t_4, v_4, tb_4 = exception.type, exception.value, exception.traceback

    assert isinstance(exception, tuple)
    assert len(exception) == 3
    assert exception == reference
    assert reference == exception
    assert not (exception != reference)
    assert not (reference != exception)
    assert all(t == ZeroDivisionError for t in (t_1, t_2, t_3, t_4))
    assert all(isinstance(v, ZeroDivisionError) for v in (v_1, v_2, v_3, v_4))
    assert all(isinstance(tb, types.TracebackType) for tb in (tb_1, tb_2, tb_3, tb_4)) 
Example #28
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_exception_raising(writer, exception):
    logger.add(writer)

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

    with pytest.raises(ZeroDivisionError):
        a()

    assert writer.read() == "" 
Example #29
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_exclude_exception_raising(writer, exclude, exception):
    logger.add(writer)

    @logger.catch(exception, exclude=exclude)
    def a():
        1 / 0

    with pytest.raises(ZeroDivisionError):
        a()

    assert writer.read() == "" 
Example #30
Source File: test_catch_exceptions.py    From loguru with MIT License 5 votes vote down vote up
def test_exclude_exception_not_raising(writer, exclude, exception):
    logger.add(writer)

    @logger.catch(exception, exclude=exclude)
    def a():
        1 / 0

    a()
    assert writer.read().endswith("ZeroDivisionError: division by zero\n")