1

当我的数据库出现故障时,Sentry 立即被 psycopg2 的OperationalError: could not connect to server: Connection refused. 由于OperationalError可以在无法访问的数据库之外的其他情况下抛出,所以我不能盲目地使用RAVEN_CONFIG's忽略它IGNORE_EXCEPTIONS

我试图为 Django logging 编写一个过滤器,但它不起作用。它正确地拦截了异常,但仍然以某种方式将其冒泡。这是过滤器:

def skip_unreachable_database(record):
    """Avoid flooding Sentry when the database is down"""
    if record.exc_info:
        print '>>>', record.exc_info
        exc_type, exc_value = record.exc_info[:2]
        if isinstance(exc_value, OperationalError) and exc_value.message.lower().startswith('could not connect to server: connection refused'):
            return False
    return True

一张关于过滤不适用于 Raven 的票,但它已被关闭。

知道如何解决这个问题吗?

4

1 回答 1

1

这是我的想法(现在):

1/ 过滤掉所有OperationalError使用 Raven 的配置:

RAVEN_CONFIG = {
    # [...]
    'IGNORE_EXCEPTIONS': [
        'OperationalError',
    ],
}

2/ 为这些异常添加专用过滤器、记录器和日志文件,这样它们就不会丢失:

def operational_errors_only(record):
    """Only catch OperationalError exceptions"""
    if record.exc_info:
        exc_type, exc_value = record.exc_info[:2]
        if isinstance(exc_value, OperationalError):
            return True
    return False

LOGGING = {
    # [...]
    'filters': {
        'operational_errors_only': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': operational_errors_only,
        },
    },
    'handlers': {
        'operationalerrors': {
            'mode': 'a',
            'class': 'common_src.logutils.FallbackWatchedFileHandler',
            'filename': '/path/to/operationalerrors.log',
            'formatter': 'verbose',
            'filters': ['operational_errors_only'],
        },
    },
    'loggers': {
        '': {
            'handlers': ['console', 'sentry', 'operationalerrors'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}
于 2014-09-22T12:40:54.653 回答