sentry-python icon indicating copy to clipboard operation
sentry-python copied to clipboard

Distinguish between `logger.error` and `logger.exception` in `LoggingIntegration`

Open sentrivana opened this issue 1 month ago • 1 comments

Problem Statement

The problem is twofold:

  1. Since both logger.error() and logger.exception() create ERROR-level logs in Python, there is currently no way to make logger.exception() create an error event, but not logger.error().
  2. Currently, the default behavior is to create error events from any ERROR logs. This is not great:
  • users often don't know where the errors are coming from (https://github.com/getsentry/sentry-python/issues/4187)
  • it often happens that LoggingIntegration captures an error before a dedicated integration that has more context, so the error arrives in Sentry with worse data than it could've had had it been captured by the dedicated integration

Conceptually it makes more sense for the default behavior to be to only create events automatically from logger.exception() rather than all ERROR logs. But in order to do that (in the next major), we need to be able to distinguish logs emitted via logger.error() and logger.exception(). Changing the default is tracked in https://github.com/getsentry/sentry-python/issues/4994.

Solution Brainstorm

Internally in Python, logger.exception() and logger.error() are the same, except logger.exception() additionally stores exc_info on the resulting log record. We can use this in our handler to determine whether something is an exception or a regular ERROR log.

We then need to provide a way to toggle capturing logs from logger.exception(). Probably need a new integration-level option here (i.e., not reusing the existing event_level).

sentrivana avatar Oct 22 '25 14:10 sentrivana