Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Handle Logger.exception() outside "except" block #635

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ import pathlib, tomllib
for sponsor in tomllib.loads(pathlib.Path("pyproject.toml").read_text())["tool"]["sponcon"]["sponsors"]:
print(f'<a href="{sponsor["url"]}"><img title="{sponsor["title"]}" src="_static/sponsors/{sponsor["img"]}" width="190" height="60" /></a>')
]]] -->
<a href="https://www.variomedia.de/"><img title="Variomedia AG" src="/en/latest/_static/sponsors/Variomedia.svg" width="200" height="60" /></a>
<a href="https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek"><img title="Tidelift" src="/en/latest/_static/sponsors/Tidelift.svg" width="200" height="60" /></a>
<a href="https://klaviyo.com/"><img title="Klaviyo" src="/en/latest/_static/sponsors/Klaviyo.svg" width="200" height="60" /></a>
<a href="https://filepreviews.io/"><img title="FilePreviews" src="/en/latest/_static/sponsors/FilePreviews.svg" width="200" height="60" /></a>
<a href="https://www.variomedia.de/"><img title="Variomedia AG" src="_static/sponsors/Variomedia.svg" width="190" height="60" /></a>
<a href="https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek"><img title="Tidelift" src="_static/sponsors/Tidelift.svg" width="190" height="60" /></a>
<a href="https://klaviyo.com/"><img title="Klaviyo" src="_static/sponsors/Klaviyo.svg" width="190" height="60" /></a>
<a href="https://filepreviews.io/"><img title="FilePreviews" src="_static/sponsors/FilePreviews.svg" width="190" height="60" /></a>
<!-- [[[end]]] -->

```{include} ../README.md
Expand Down
3 changes: 0 additions & 3 deletions src/structlog/_frames.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ def _format_exception(exc_info: ExcInfo) -> str:

Shamelessly stolen from stdlib's logging module.
"""
if exc_info == (None, None, None): # type: ignore[comparison-overlap]
return "MISSING"

sio = StringIO()

traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, sio)
Expand Down
16 changes: 9 additions & 7 deletions src/structlog/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
NamedTuple,
Sequence,
TextIO,
cast,
)

from ._frames import (
Expand Down Expand Up @@ -407,10 +408,10 @@ def __init__(
def __call__(
self, logger: WrappedLogger, name: str, event_dict: EventDict
) -> EventDict:
exc_info = event_dict.pop("exc_info", None)
if exc_info:
exc_info = _figure_out_exc_info(event_dict.pop("exc_info", None))
if exc_info and exc_info != (None, None, None):
event_dict["exception"] = self.format_exception(
_figure_out_exc_info(exc_info)
cast(ExcInfo, exc_info)
)

return event_dict
Expand Down Expand Up @@ -586,7 +587,7 @@ def __call__(
return event_dict


def _figure_out_exc_info(v: Any) -> ExcInfo:
def _figure_out_exc_info(v: Any) -> ExcInfo | tuple[None, None, None]:
"""
Depending on the Python version will try to do the smartest thing possible
to transform *v* into an ``exc_info`` tuple.
Expand All @@ -598,7 +599,8 @@ def _figure_out_exc_info(v: Any) -> ExcInfo:
return v

if v:
return sys.exc_info() # type: ignore[return-value]
# Can be "(None, None, None)" if not called inside an error context:
return sys.exc_info()

return v

Expand Down Expand Up @@ -642,8 +644,8 @@ def __call__(
exc = event_dict.pop("exception", None)
if exc is None:
exc_info = _figure_out_exc_info(event_dict.pop("exc_info", None))
if exc_info:
exc = _format_exception(exc_info)
if exc_info and exc_info != (None, None, None):
exc = _format_exception(cast(ExcInfo, exc_info))

if exc:
print(exc, file=self._file)
Expand Down
4 changes: 1 addition & 3 deletions tests/processors/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,4 @@ def test_no_exception(self, ei):
"""
A missing exception does not blow up.
"""
assert {"exception": "MISSING"} == format_exc_info(
None, None, {"exc_info": ei}
)
assert {} == format_exc_info(None, None, {"exc_info": ei})
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this okay for you, @hynek ? The format_exc_info() handled the (None, None, None) (even though its signature suggested that exc_info: ExcInfo) and returned {"excepiton": "MISSING"}.

Now, (None, None, None) will no longer be passed to it and thus there will no longer be a MISSING.

73 changes: 73 additions & 0 deletions tests/test_tracebacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

import pytest

import structlog

from structlog import tracebacks


Expand Down Expand Up @@ -730,3 +732,74 @@ def test_json_traceback_value_error(
monkeypatch.setattr(kwargs["suppress"][0], "__file__", None)
with pytest.raises(ValueError, match=next(iter(kwargs.keys()))):
tracebacks.ExceptionDictTransformer(**kwargs)


class TestLogException:
"""
Higher level "integration tests" for "Logger.exception()".
"""

@pytest.fixture()
def cap_logs(self) -> structlog.testing.LogCapture:
"""
Create a LogCapture to be used as processor and fixture for retrieving
logs in tests.
"""
return structlog.testing.LogCapture()

@pytest.fixture()
def logger(
self, cap_logs: structlog.testing.LogCapture
) -> structlog.Logger:
"""
Create a logger with the dict_tracebacks and a LogCapture processor.
"""
old_processors = structlog.get_config()["processors"]
structlog.configure([structlog.processors.dict_tracebacks, cap_logs])
logger = structlog.get_logger("dict_tracebacks")
try:
yield logger
finally:
structlog.configure(processors=old_processors)

def test_log_explicit_exception(
self, logger: structlog.Logger, cap_logs: structlog.testing.LogCapture
) -> None:
"""
The log row contains a traceback when "Logger.exception()" is
explicitly called with an exception instance.
"""
try:
1 / 0
except ZeroDivisionError as e:
logger.exception("onoes", exception=e)

log_row = cap_logs.entries[0]
assert log_row["exception"][0]["exc_type"] == "ZeroDivisionError"

def test_log_implicit_exception(
self, logger: structlog.Logger, cap_logs: structlog.testing.LogCapture
) -> None:
"""
The log row contains a traceback when "Logger.exception()" is called
in an "except" block but without explicitly passing the exception.
"""
try:
1 / 0
except ZeroDivisionError:
logger.exception("onoes")

log_row = cap_logs.entries[0]
assert log_row["exception"][0]["exc_type"] == "ZeroDivisionError"

def test_no_exception(
self, logger: structlog.Logger, cap_logs: structlog.testing.LogCapture
) -> None:
"""
"Logger.exception()" should not be called outside an "except" block
but this cases is gracefully handled and does not lead to an exception.

See: https://github.com/hynek/structlog/issues/634
"""
logger.exception("onoes")
assert [{"event": "onoes", "log_level": "error"}] == cap_logs.entries