Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Loguru Exception Handling and Tracebacks

Learn how to capture and format exception tracebacks with Python Loguru, control backtrace and diagnose options, and integrate with standard logging.

~4 min readPython
#loguru#exception handling#tracebacks#python logging
A stylized terminal window showing a Python traceback with Loguru's colored formatting and a catch decorator.

Loguru changes how Python exception tracebacks appear in logs when you record them through its API. It formats the stack in a readable way and can optionally include local variable values. This article covers how to capture exceptions with Loguru, how to control traceback depth and diagnostic details, and how to avoid common integration pitfalls.

What Loguru Does by Default

Loguru adds a default handler that writes records to stderr. This handler stays active until you call logger.remove(); adding a file handler does not disable it. It does not, however, install a global hook for unhandled exceptions. If an exception is raised outside a logger call, Python's normal traceback printing takes over, and Loguru does not add that exception to your configured sinks.

For example, this code logs nothing to app.log:

python
from loguru import logger logger.add('app.log', level='ERROR') def divide(a, b): return a / b divide(1, 0)

The exception is unhandled, so the interpreter writes the standard traceback to stderr. To capture an unhandled exception with Loguru, wrap the code that may raise with @logger.catch or call logger.exception() from an except block.

Capturing Exceptions with @logger.catch

The @logger.catch decorator is the simplest way to ensure an exception is logged with its traceback. It wraps a function and logs exceptions it is configured to catch (by default, subclasses of Exception), then re-raises them by default. You can change this behavior with the reraise parameter.

python
from loguru import logger @logger.catch def risky_operation(): return 1 / 0 risky_operation()

The traceback is logged at ERROR level, and the exception is re-raised. If you want to swallow the exception and return a default value, set reraise=False:

python
@logger.catch(reraise=False, default=None) def safe_divide(a, b): return a / b

The decorator also accepts level, message, and exception parameters. level and message control the log record, while exception controls which exception classes are caught.

Logging Exception Objects with logger.exception()

Inside an except block, logger.exception() logs the current exception with its traceback. This method is equivalent to logger.error('...', exc_info=True) in the standard logging module. It is the most direct way to record an exception that you have already caught.

python
try: result = int('not a number') except ValueError as e: logger.exception('Failed to parse input')

The output includes the exception type, message, and the full stack trace at the point where the exception was raised. If you need to log an exception object that is not currently being handled, use logger.opt(exception=e):

python
try: result = int('not a number') except ValueError as e: logger.opt(exception=e).error('Custom message')

This allows you to log an arbitrary exception with its traceback, even when it is not the exception currently being processed.

Customizing Traceback Formatting and Depth

Loguru's traceback formatting is controlled by two options in logger.add(): backtrace and diagnose. The backtrace option controls whether the full stack trace is shown, including frames outside the current exception context. Setting backtrace=False limits the traceback to the frames between the try block and the exception, which can reduce noise.

The diagnose option includes variable values in the traceback. This is helpful during development but can leak sensitive information in production. Set diagnose=False to hide variable values.

python
logger.add('app.log', backtrace=False, diagnose=False)

You can also control whether and where the formatted exception appears by using the {exception} placeholder in the handler's format string. The default Loguru format includes this placeholder. For example, this format includes it explicitly:

python
logger.add('app.log', format='{time} | {level} | {message} | {exception}')

The backtrace and diagnose options determine how detailed that traceback is. If you only want the exception message for hot paths, extract it directly in the log message and do not log the full traceback.

Using Exception Groups and Chained Exceptions

Python 3.11 introduced exception groups and the except* syntax. Python's traceback formatting preserves these structures, so when such an exception is logged, the traceback includes the nested exceptions. For chained exceptions (using raise ... from ...), Loguru shows the cause chain.

python
try: raise ValueError('original') from RuntimeError('cause') except Exception: logger.exception('Chained exception')

The log entry will include both the cause and the original exception. This follows the same traceback behavior as Python's standard library.

Performance and Production Considerations for Traceback Logging

Formatting a traceback is CPU-intensive because it involves walking the stack and formatting each frame. In high-throughput applications, logging a traceback for every error can become a bottleneck. Use the backtrace=False option to reduce the amount of work, and consider logging only the exception message in hot paths.

The diagnose option also has a performance cost because it inspects variable values. In production, set diagnose=False to avoid the overhead and to prevent sensitive data from appearing in logs. If you need tracebacks for debugging, enable them only in a development environment or via a runtime flag.

Another production concern is log volume. Tracebacks can be large, especially with deep call stacks. Use log rotation and retention policies to manage disk usage. Loguru's rotation and retention parameters in logger.add() help with this.

Common Pitfalls When Combining Loguru with Other Logging Handlers

Loguru does not use the standard logging module by default. If your application also uses libraries that write to the standard logging system, create a custom logging.Handler that forwards records to Loguru:

python
import logging from loguru import logger class InterceptHandler(logging.Handler): def emit(self, record): try: level = logger.level(record.levelname).name except ValueError: level = record.levelno frame, depth = logging.currentframe(), 2 while frame.f_code.co_filename == logging.__file__: frame = frame.f_back depth += 1 logger.opt(depth=depth, exception=record.exc_info).log( level, record.getMessage() ) logging.basicConfig(handlers=[InterceptHandler()], level=0)

This ensures that tracebacks from third-party libraries appear in Loguru's output with Loguru's formatting. Without this, logs from standard logging users will not go through Loguru.

Another pitfall is double logging. If you forward standard logging records to Loguru but also keep a separate standard logging handler, the same record can be written twice. Choose one system as the primary sink and use the other only for forwarding.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.