Search code examples
pythonloggingsentryraven

Sentry - how to log only exceptions, not logger


I want to use sentry for logging test exceptions. So I configured it:

# tests/__init__.py

from raven import Client
from raven.conf import setup_logging
from raven.handlers.logging import SentryHandler

client = Client(dsn='here goes dsn')
handler = SentryHandler(client, level=logging.ERROR)
setup_logging(handler)

When I run my test:

# tests/test_lolz.py

logger = logging.getLogger(__name__)

def test_log():
    logger.warning('do not want to see this - warn')
    logger.error('do not want to see this - error')
    1 / 0  # yolo

I see both in sentry dashboard: logger error and exception

With logging level critical nothing appears.

So, is there a method to log only exceptions, but not regular logs?


Solution

  • Sentry doesn't currently provide a way to say "only capture log events which have an exception attached", but you could write a logging.Filter for it. The Python docs are a bit sparse, but here's an example of a filter:

    https://docs.python.org/2/howto/logging-cookbook.html#using-filters-to-impart-contextual-information

    You'd basically want to detect if the exception info is present on the entry, and if it is, return True (telling it to capture the entry).