Exceptions#
While you should use a proper crash reporter like Sentry in production, structlog has helpers for formatting exceptions for humans and machines.
All structlog’s exception features center around passing an exc_info key-value pair in the event dict.
There are three possible behaviors depending on its value:
If the value is a tuple, render it as if it was returned by
sys.exc_info().If the value is an Exception, render it.
If the value is true but no tuple, call
sys.exc_info()and render that.
If there is no exc_info key or false, the event dict is not touched.
This behavior is analog to the one of the stdlib’s logging.
Transformations#
structlog comes with structlog.processors.ExceptionRenderer that deduces and removes the exc_info key as outlined above, calls a user-supplied function with the synthesized exc_info, and stores its return value in the exception key.
The most common use-cases are already covered by the following processors:
structlog.processors.format_exc_info()Formats it to a flat string like the standard library would on the console.
structlog.processors.dict_tracebacksUses
structlog.tracebacks.ExceptionDictTransformerto give you a structured and JSON-serializableexceptionkey.
Customizing Dict Tracebacks#
structlog.tracebacks.ExceptionDictTransformer can be customized with a number of parameters.
If these prove insufficient, see Custom Filtering of Dict Tracebacks.
Console rendering#
Our Console Output’s structlog.dev.ConsoleRenderer takes an exception_formatter argument that allows for customizing the output of exceptions.
structlog.dev.plain_traceback()Is the default if Rich is not installed. As the name suggests, it renders a plain traceback.
structlog.dev.RichTracebackFormatterUses Rich to render a colorful traceback. It’s a class because it allows for customizing the output by passing arguments to Rich.
It’s the default if Rich is installed.
See also
Console Output for more information on structlog’s console features.
Deprecated since version 26.1.0: Support for better-exceptions is deprecated and will be removed in a future release. Use Rich instead.