Skip to content

How do I log out exceptions without pretty stack trace and without warning? #775

@miversen33

Description

@miversen33

Hello!

I recently stumbled across structlog and man I love it! Its quickly become my go to logging library for python :)

That said, something that has been bothering me is the handling of exceptions in structlog. Take below for example

#!/usr/bin/env python

import logging

import structlog
from structlog.dev import ConsoleRenderer

structlog.configure()

log_level = logging.getLevelNamesMapping()["DEBUG"]

processors: list = [
    structlog.contextvars.merge_contextvars,
    structlog.processors.add_log_level,
    structlog.processors.TimeStamper(fmt="iso"),
    ConsoleRenderer(sort_keys=True, colors=True),
]
structlog.configure(
    processors=processors,
    wrapper_class=structlog.make_filtering_bound_logger(log_level),
    logger_factory=structlog.stdlib.LoggerFactory(),
)

log = structlog.get_logger()
log.debug("test message")

try:
    raise ValueError("I want this exception to be pretty")
except ValueError as err:
    log.exception(err)

try:
    raise ValueError("I don't want this exception to be pretty")
except ValueError as err:
    log.error("unhandled exception occurred", exception=repr(err))

What I would expect here is to see the first exception in pretty format, and the second to not be pretty. And indeed, I do see that

Image

But I don't want the warning about pretty exceptions

/home/miversen/git/melodocity/.venv/lib/python3.13/site-packages/structlog/_base.py:173: UserWarning: Remove format_exc_info from your processor chain if you want pretty exceptions.
event_dict = proc(self._logger, method_name, event_dict)

I had read that you can use exc_info=False as a key in the log, but that doesn't help. How do I make structlog accept that sometimes I want pretty exceptions, other times I don't. I don't always need a stacktrace

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions