如何忽略Sentry Python SDK中的记录器

时间:2018-10-22 10:38:35

标签: python django sentry

我正在使用sentry-python SDK从django服务器捕获异常。

sentry capture

我不想捕获上面的django.security.DisallowedHost。 如何删除该记录器的哨兵处理?

我在下面附加了服务器配置。

settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
       'null': {
            'level': 'DEBUG',
            'class': 'logging.NullHandler',
        },
    },
    'loggers': {
        # Silence SuspiciousOperation.DisallowedHost exception ('Invalid
        # HTTP_HOST' header messages). Set the handler to 'null' so we don't
        # get those annoying emails.
        'django.security.DisallowedHost': {
            'handlers': ['null'],
            'propagate': False,
        },
    }
}

sentry_sdk.init(
    dsn=os.environ['SENTRY_DSN'],
    integrations=[DjangoIntegration()],
    send_default_pii=True,
    release=f"{os.environ['STAGE']}@{os.environ['VERSION']}",
)

2 个答案:

答案 0 :(得分:6)

快速解答

https://docs.sentry.io/platforms/python/logging/#ignoring-a-logger

from sentry_sdk.integrations.logging import ignore_logger


ignore_logger("a.spammy.logger")

logger = logging.getLogger("a.spammy.logger")
logger.error("hi")  # no error sent to sentry

一种通过某些特征忽略事件的更精细但通用的方法

请参见https://docs.sentry.io/learn/breadcrumbs/?platform=python#breadcrumb-customization

import sentry_sdk

def before_breadcrumb(crumb, hint):
    if crumb.get('category', None) == 'a.spammy.Logger':
        return None
    return crumb

def before_send(event, hint):
    if event.get('logger', None) == 'a.spammy.Logger':
        return None
    return event

sentry_sdk.init(before_breadcrumb=before_breadcrumb, before_send=before_send)

答案 1 :(得分:3)

在sentry_sdk下,我不得不在before_send中使用以下代码来使其忽略django.security.DisallowedHost异常。

def before_send(event, hint):
        """Don't log django.DisallowedHost errors in Sentry."""
        if 'log_record' in hint:
            if hint['log_record'].name == 'django.security.DisallowedHost':
                return None

        return event