如何防止哨兵在 Django 本地服务器上记录错误?

How to prevent sentry from logging errors while on Django local server?

当我在本地服务器上工作时(即 http://127.0.0.1:8000/),我试图阻止 Sentry 将错误记录到我的 Sentry 仪表板。我希望哨兵将错误记录到我的仪表板的唯一时间是我的代码在生产中。我该怎么做?我已经在下面尝试过,但它不起作用:

if DEBUG == True
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],
    
        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,
    
        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
    )

这样试试:

  if not DEBUG:
    sentry_sdk.init(
        dsn="SENTRY_DSN",
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
    )

您可以通过两种方式执行此操作:

第一个选项是 import sys 并检查 runserver(参考:)

import sys

if (len(sys.argv) >= 2 and sys.argv[1] != 'runserver'):
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
)

第二个选项是在 settings.py 中指定环境类型。例如,如果您的生产服务器是 Heroku,您可以在 Heroku 或您的 .env 文件中创建一个 env_type 变量并将其设置为 'HEROKU',然后像这样使用它:

env_type = os.environ.get('env_type', 'LOCAL')

if env_type == 'HEROKU':
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
)

dsn 设置为 None 将 no-op 所有 SDK 操作,因此您的配置应该有效,除非您还在本地环境中设置 SENTRY_DSN 变量。