def setup_once(): DjangoIntegration.setup_once() from django.core.handlers.base import BaseHandler old_get_response = BaseHandler.get_response def sentry_patched_get_response(self, request): hub = Hub.current integration = hub.get_integration(DjangoIntegration) if integration is not None: with hub.configure_scope() as scope: scope.add_event_processor( _make_event_processor(weakref.ref(request), integration) ) return old_get_response(self, request) BaseHandler.get_response = sentry_patched_get_response
def post_setup(cls): sentry_sdk.init(dsn=cls.SENTRY_DSN, integrations=[DjangoIntegration()])
""" import environ import os from urllib.parse import urlparse # If using in your own project, update the project namespace below from .settings import * # Sentry integration from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.redis import RedisIntegration sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], integrations=[DjangoIntegration(), RedisIntegration()], # 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 ) env = environ.Env( # set casting, default value DEBUG=(bool, False))
# Keys will be set in core.apps.Config.ready() 'JWT_PUBLIC_KEY': '?', # 'JWT_PRIVATE_KEY': wallet.get_private(), # 'JWT_PRIVATE_KEY': None, 'JWT_ALGORITHM': 'RS256', } SENTRY_DSN = env('SENTRY_DSN', default=None) # noqa: F405 if SENTRY_DSN: # pragma: no cover sentry_sdk.init( dsn=SENTRY_DSN, # by default this is False, must be set to True so the library attaches the request data to the event send_default_pii=True, integrations=[DjangoIntegration(), CeleryIntegration()], ) if DEBUG: # pragma: no cover INSTALLED_APPS += ( # noqa 'debug_toolbar', ) MIDDLEWARE += ( # noqa 'debug_toolbar.middleware.DebugToolbarMiddleware', ) DEBUG_TOOLBAR_CONFIG = { 'SHOW_TEMPLATE_CONTEXT': True, }
"handlers": ["console"], "propagate": False }, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, }, } # Sentry # ------------------------------------------------------------------------------ SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.ERROR, # Send errors as events ) integrations = [sentry_logging, DjangoIntegration()] sentry_sdk.init( dsn=SENTRY_DSN, integrations=integrations, environment=env("SENTRY_ENVIRONMENT", default="production"), traces_sample_rate=env.float("SENTRY_TRACES_SAMPLE_RATE", default=0.0), ) # Your stuff... # ------------------------------------------------------------------------------
def configure_sdk(): from sentry_sdk.integrations.logging import LoggingIntegration from sentry_sdk.integrations.django import DjangoIntegration from sentry_sdk.integrations.celery import CeleryIntegration from sentry_sdk.integrations.redis import RedisIntegration assert sentry_sdk.Hub.main.client is None sdk_options = dict(settings.SENTRY_SDK_CONFIG) relay_dsn = sdk_options.pop("relay_dsn", None) internal_project_key = get_project_key() upstream_dsn = sdk_options.pop("dsn", None) sdk_options["traces_sampler"] = traces_sampler if upstream_dsn: upstream_transport = make_transport(get_options(dsn=upstream_dsn, **sdk_options)) else: upstream_transport = None if relay_dsn: relay_transport = make_transport(get_options(dsn=relay_dsn, **sdk_options)) elif internal_project_key and internal_project_key.dsn_private: relay_transport = make_transport( get_options(dsn=internal_project_key.dsn_private, **sdk_options) ) else: relay_transport = None _override_on_full_queue(relay_transport, "internal.uncaptured.events.relay") _override_on_full_queue(upstream_transport, "internal.uncaptured.events.upstream") class MultiplexingTransport(sentry_sdk.transport.Transport): def capture_envelope(self, envelope): # Assume only transactions get sent via envelopes if options.get("transaction-events.force-disable-internal-project"): return self._capture_anything("capture_envelope", envelope) def capture_event(self, event): if event.get("type") == "transaction" and options.get( "transaction-events.force-disable-internal-project" ): return self._capture_anything("capture_event", event) def _capture_anything(self, method_name, *args, **kwargs): # Upstream should get the event first because it is most isolated from # the this sentry installation. if upstream_transport: metrics.incr("internal.captured.events.upstream") # TODO(mattrobenolt): Bring this back safely. # from sentry import options # install_id = options.get('sentry:install-id') # if install_id: # event.setdefault('tags', {})['install-id'] = install_id getattr(upstream_transport, method_name)(*args, **kwargs) if relay_transport and options.get("store.use-relay-dsn-sample-rate") == 1: if is_current_event_safe(): metrics.incr("internal.captured.events.relay") getattr(relay_transport, method_name)(*args, **kwargs) else: metrics.incr("internal.uncaptured.events.relay", skip_internal=False) sentry_sdk.init( transport=MultiplexingTransport(), integrations=[ DjangoIntegration(), CeleryIntegration(), LoggingIntegration(event_level=None), RustInfoIntegration(), RedisIntegration(), ], **sdk_options )
from madewithwagtail.settings import APPLICATION_VERSION, PROJECT, ENVIRONMENT SENTRY_RELEASE = APPLICATION_VERSION SENTRY_ENVIRONMENT = ENVIRONMENT _ENVVARS = [ StringVariable("SENTRY_DSN_BED", default=""), StringVariable("SENTRY_DSN_FED", default=""), StringVariable("SENTRY_CSP_URL", default=""), ] fill(_ENVVARS, vars(), prefix="") sentry_logging = LoggingIntegration(level=logging.INFO, event_level=logging.ERROR) sentry_sdk.init( dsn=SENTRY_DSN_BED, integrations=[DjangoIntegration(), sentry_logging], release=SENTRY_RELEASE, environment=SENTRY_ENVIRONMENT, ) # CSP is not currently configured for madewithwagtail, so this is # a no-op, but might as well leave it in case they do CSP_REPORT_URI = [ "{base_url}&sentry_release={release}&sentry_environment={environment}". format(base_url=SENTRY_CSP_URL, release=SENTRY_RELEASE, environment=SENTRY_ENVIRONMENT) ]
"LOCATION": _REDIS_URL, "OPTIONS": { "SERIALIZER": "django_redis.serializers.msgpack.MSGPackSerializer", }, } # Sentry integration _SENTRY_DSN = os.environ.get("JAWANNDENN_SENTRY_DSN") if _SENTRY_DSN: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration _sentry_integrations = [DjangoIntegration()] if _USE_REDIS_CACHE: from sentry_sdk.integrations.redis import RedisIntegration _sentry_integrations.append(RedisIntegration()) sentry_sdk.init( dsn=_SENTRY_DSN, integrations=_sentry_integrations, send_default_pii=False ) AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", )
} # redis REDIS_HOST = env.str('REDIS_HOST', 'redis://*****:*****@codium.co>') ALLOWED_EMAIL_DOMAINS = env.list('ALLOWED_EMAIL_DOMAINS', default=['*']) # Email address validator # sentry sentry_sdk.init(integrations=[DjangoIntegration(), CeleryIntegration()], send_default_pii=True)
def init_django_sentry(sentry_init): sentry_init(integrations=[DjangoIntegration()], send_default_pii=True)
def test_sql_psycopg2_placeholders(sentry_init, capture_events): sentry_init( integrations=[DjangoIntegration()], send_default_pii=True, _experiments={"record_sql_params": True}, ) from django.db import connections if "postgres" not in connections: pytest.skip("postgres tests disabled") import psycopg2.sql sql = connections["postgres"].cursor() events = capture_events() with pytest.raises(DataError): names = ["foo", "bar"] identifiers = [psycopg2.sql.Identifier(name) for name in names] placeholders = [ psycopg2.sql.Placeholder(var) for var in ["first_var", "second_var"] ] sql.execute("create table my_test_table (foo text, bar date)") query = psycopg2.sql.SQL( "insert into my_test_table ({}) values ({})").format( psycopg2.sql.SQL(", ").join(identifiers), psycopg2.sql.SQL(", ").join(placeholders), ) sql.execute(query, {"first_var": "fizz", "second_var": "not a date"}) capture_message("HI") event, = events for crumb in event["breadcrumbs"]: del crumb["timestamp"] assert event["breadcrumbs"][-2:] == [ { "category": "query", "data": { "db.paramstyle": "format" }, "message": "create table my_test_table (foo text, bar date)", "type": "default", }, { "category": "query", "data": { "db.params": { "first_var": "fizz", "second_var": "not a date" }, "db.paramstyle": "format", }, "message": 'insert into my_test_table ("foo", "bar") values (%(first_var)s, ' "%(second_var)s)", "type": "default", }, ]
}, 'atualiza-dados-das-escolas': { 'task': 'sme_terceirizadas.escola.tasks.atualiza_dados_escolas', 'schedule': crontab(hour=0, minute=30) }, 'ativa-desativa-vinculos-alimentacao': { 'task': 'sme_terceirizadas.cardapio.tasks.ativa_desativa_vinculos_alimentacao_com_periodo_escolar_e_tipo_unidade_escolar', # noqa E501 'schedule': crontab(hour=1, minute=0) } } # reset password PASSWORD_RESET_TIMEOUT_DAYS = 1 sentry_sdk.init(dsn=env('SENTRY_URL'), integrations=[DjangoIntegration()]) logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level': 'DEBUG', },
"handlers": { "null": {"class": "logging.NullHandler",}, "mail_admins": { "level": "ERROR", "class": "django.utils.log.AdminEmailHandler", "filters": ["require_debug_false"], }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "filters": ["request_id"], "formatter": "standard", }, }, "loggers": { "": {"handlers": ["console"], "level": "INFO"}, "django.security.DisallowedHost": {"handlers": ["null"], "propagate": False,}, "django.request": {"handlers": ["mail_admins"], "level": "ERROR", "propagate": True,}, "log_request_id.middleware": { "handlers": ["console"], "level": "DEBUG", "propagate": False, }, }, } JS_REVERSE_EXCLUDE_NAMESPACES = ["admin"] # Sentry sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()], release=COMMIT_SHA)
def init_logger(self): """ Initialize the logger. Call exactly once. """ assert (self.name is not None) assert (self.author is not None) self.handlers = {} if self.is_root: self.log = logging.getLogger() else: self.log = logging.getLogger(self.name) if not self.propagate: self.log.propagate = False # set the root log level if self.verbose: self.log.setLevel(logging.DEBUG) else: self.log.setLevel(logging.INFO) if self.log.hasHandlers(): self.log.info("Logger already initialized.") # create file handler if self.log_directory is None: self.log_directory = appdirs.user_log_dir(self.name, self.author) if self.log_directory is not None: if self.delete_existing_log_files: for file_path in glob( os.path.join(self.log_directory, "*%s" % self.log_extension)): try: os.remove(file_path) except OSError: pass os.makedirs(self.log_directory, exist_ok=True) self.log_path = os.path.join( self.log_directory, "%s%s" % (self.name, self.log_extension)) file_handler = logging.handlers.RotatingFileHandler( self.log_path, maxBytes=self.max_bytes, backupCount=self.backup_count) file_handler.setFormatter(self.log_formatter) if self.verbose: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.INFO) self.log.addHandler(file_handler) self.handlers[HandlerType.File] = file_handler self.log.info('log file path : "%s" ("%s")' % (self.log_path, os.path.abspath(self.log_path))) if self.gui: # GUI will only pop up a dialog box - it's important that GUI not try to output to stdout or stderr # since that would likely cause a permissions error. dialog_box_handler = DialogBoxHandler(self.rate_limits) if self.verbose: dialog_box_handler.setLevel(logging.WARNING) else: dialog_box_handler.setLevel(logging.ERROR) self.log.addHandler(dialog_box_handler) self.handlers[HandlerType.DialogBox] = dialog_box_handler else: console_handler = logging.StreamHandler() console_handler.setFormatter(self.log_formatter) if self.verbose: console_handler.setLevel(logging.INFO) else: console_handler.setLevel(logging.WARNING) self.log.addHandler(console_handler) self.handlers[HandlerType.Console] = console_handler string_list_handler = BalsaStringListHandler( self.max_string_list_entries) string_list_handler.setFormatter(self.log_formatter) string_list_handler.setLevel(logging.INFO) self.log.addHandler(string_list_handler) self.handlers[HandlerType.StringList] = string_list_handler # setting up Sentry error handling # For the Client to work you need a SENTRY_DSN environmental variable set, or one must be provided. if self.use_sentry: sample_rate = 0.0 if self.inhibit_cloud_services else 1.0 integrations = [] if self.use_sentry_django: from sentry_sdk.integrations.django import DjangoIntegration integrations.append(DjangoIntegration()) if self.use_sentry_flask: from sentry_sdk.integrations.flask import FlaskIntegration integrations.append(FlaskIntegration()) if self.use_sentry_lambda: from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration integrations.append(AwsLambdaIntegration()) if self.use_sentry_sqlalchemy: from sentry_sdk.integrations.sqlalchemy import SqlalchemyIntegration integrations.append(SqlalchemyIntegration()) if self.use_sentry_celery: from sentry_sdk.integrations.celery import CeleryIntegration integrations.append(CeleryIntegration()) if self.sentry_dsn is None: if 'SENTRY_DSN' not in os.environ: raise ValueError(f"Missing sentry_dsn") else: sentry_sdk.init( dsn=os.environ['SENTRY_DSN'], sample_rate=sample_rate, integrations=integrations, ) else: sentry_sdk.init( dsn=self.sentry_dsn, sample_rate=sample_rate, integrations=integrations, ) # error handler for callback on error or above # (this is last since the user may do a sys.exit() in the error callback) if self.error_callback is not None: error_callback_handler = BalsaNullHandler(self.error_callback) error_callback_handler.setLevel(logging.ERROR) self.log.addHandler(error_callback_handler) self.handlers[HandlerType.Callback] = error_callback_handler
} # Sentry # ------------------------------------------------------------------------------ SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.ERROR, # Send errors as events ) {%- if cookiecutter.use_celery == 'y' %} integrations = [ sentry_logging, DjangoIntegration(), CeleryIntegration(), RedisIntegration(), ] {% else %} integrations = [sentry_logging, DjangoIntegration(), RedisIntegration()] {% endif -%} sentry_sdk.init( dsn=SENTRY_DSN, integrations=integrations, environment=env("SENTRY_ENVIRONMENT", default="production"), traces_sample_rate=env.float("SENTRY_TRACES_SAMPLE_RATE", default=0.0), ) {% endif %} # Your stuff...
def plugin_settings(settings): # pylint: disable=function-redefined """ Set of plugin settings used by the Open Edx platform. More info: https://github.com/edx/edx-platform/blob/master/openedx/core/djangoapps/plugins/README.rst """ settings.EOX_CORE_BEARER_AUTHENTICATION = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_BEARER_AUTHENTICATION', settings.EOX_CORE_BEARER_AUTHENTICATION) settings.EOX_CORE_USERS_BACKEND = getattr(settings, 'ENV_TOKENS', {}).get( 'EOX_CORE_USERS_BACKEND', settings.EOX_CORE_USERS_BACKEND) settings.EOX_CORE_ENROLLMENT_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_ENROLLMENT_BACKEND', settings.EOX_CORE_ENROLLMENT_BACKEND) settings.EOX_CORE_PRE_ENROLLMENT_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_PRE_ENROLLMENT_BACKEND', settings.EOX_CORE_PRE_ENROLLMENT_BACKEND) settings.EOX_CORE_CERTIFICATES_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_CERTIFICATES_BACKEND', settings.EOX_CORE_CERTIFICATES_BACKEND) settings.EOX_CORE_COURSEWARE_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_COURSEWARE_BACKEND', settings.EOX_CORE_COURSEWARE_BACKEND) settings.EOX_CORE_GRADES_BACKEND = getattr(settings, 'ENV_TOKENS', {}).get( 'EOX_CORE_GRADES_BACKEND', settings.EOX_CORE_GRADES_BACKEND) settings.EOX_CORE_STORAGES_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_STORAGES_BACKEND', settings.EOX_CORE_STORAGES_BACKEND) settings.EOX_CORE_ENABLE_STATICFILES_STORAGE = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_ENABLE_STATICFILES_STORAGE', settings.EOX_CORE_ENABLE_STATICFILES_STORAGE) settings.EOX_CORE_STATICFILES_STORAGE = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_STATICFILES_STORAGE', settings.EOX_CORE_STATICFILES_STORAGE) if settings.EOX_CORE_ENABLE_STATICFILES_STORAGE: settings.STATICFILES_STORAGE = settings.EOX_CORE_STATICFILES_STORAGE settings.EOX_CORE_LOAD_PERMISSIONS = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_LOAD_PERMISSIONS', settings.EOX_CORE_LOAD_PERMISSIONS) settings.DATA_API_DEF_PAGE_SIZE = getattr(settings, 'ENV_TOKENS', {}).get( 'DATA_API_DEF_PAGE_SIZE', settings.DATA_API_DEF_PAGE_SIZE) settings.DATA_API_MAX_PAGE_SIZE = getattr(settings, 'ENV_TOKENS', {}).get( 'DATA_API_MAX_PAGE_SIZE', settings.DATA_API_MAX_PAGE_SIZE) settings.EDXMAKO_MODULE = getattr(settings, 'ENV_TOKENS', {}).get('EDXMAKO_MODULE', settings.EDXMAKO_MODULE) settings.EOX_CORE_COURSES_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_COURSES_BACKEND', settings.EOX_CORE_COURSES_BACKEND) settings.EOX_CORE_COURSEKEY_BACKEND = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_COURSEKEY_BACKEND', settings.EOX_CORE_COURSEKEY_BACKEND) settings.EOX_CORE_SITE_CONFIGURATION = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_SITE_CONFIGURATION', settings.EOX_CORE_SITE_CONFIGURATION) settings.EOX_CORE_COURSE_MANAGEMENT_REQUEST_TIMEOUT = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_COURSE_MANAGEMENT_REQUEST_TIMEOUT', settings.EOX_CORE_COURSE_MANAGEMENT_REQUEST_TIMEOUT) settings.EOX_CORE_USER_ENABLE_MULTI_TENANCY = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_USER_ENABLE_MULTI_TENANCY', settings.EOX_CORE_USER_ENABLE_MULTI_TENANCY) if not settings.EOX_CORE_USER_ENABLE_MULTI_TENANCY: user_origin_sources = [ 'fetch_from_unfiltered_table', ] else: user_origin_sources = settings.EOX_CORE_USER_ORIGIN_SITE_SOURCES settings.EOX_CORE_USER_ORIGIN_SITE_SOURCES = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_USER_ORIGIN_SITE_SOURCES', user_origin_sources) settings.EOX_CORE_APPEND_LMS_MIDDLEWARE_CLASSES = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_APPEND_LMS_MIDDLEWARE_CLASSES', settings.EOX_CORE_APPEND_LMS_MIDDLEWARE_CLASSES) if settings.SERVICE_VARIANT == "lms": if settings.EOX_CORE_APPEND_LMS_MIDDLEWARE_CLASSES: settings.MIDDLEWARE += [ 'eox_core.middleware.PathRedirectionMiddleware', 'eox_core.middleware.RedirectionsMiddleware' ] # Sentry Integration sentry_integration_dsn = getattr(settings, 'ENV_TOKENS', {}).get( 'EOX_CORE_SENTRY_INTEGRATION_DSN', settings.EOX_CORE_SENTRY_INTEGRATION_DSN) settings.EOX_CORE_SENTRY_IGNORED_ERRORS = getattr( settings, 'ENV_TOKENS', {}).get('EOX_CORE_SENTRY_IGNORED_ERRORS', settings.EOX_CORE_SENTRY_IGNORED_ERRORS) if sentry_sdk is not None and sentry_integration_dsn is not None: from eox_core.integrations.sentry import ExceptionFilterSentry sentry_sdk.init( before_send=ExceptionFilterSentry(), dsn=sentry_integration_dsn, integrations=[ DjangoIntegration(), ], # 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)
def SENTRY(self): if not self.DEBUG: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration return sentry_sdk.init(dsn=self.env('SENTRY_DSN'), integrations=[DjangoIntegration()])
"level": "ERROR", "handlers": ["console"], "propagate": False, }, # Errors logged by the SDK itself "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, }, } # Sentry # ------------------------------------------------------------------------------ SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.ERROR, # Send errors as events ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) # Your stuff... # ------------------------------------------------------------------------------
USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') INTERNAL_IPS = ['127.0.0.1', 'localhost'] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] LOGIN_REDIRECT_URL = "tasks:list" MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "media/") EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' django_heroku.settings(locals()) sentry_sdk.init( dsn="https://[email protected]/5289210", integrations=[DjangoIntegration()], # 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 )
def get_env_variable(environment_variable, optional=False): """Get the environment variable or return exception""" try: return os.environ[environment_variable] except KeyError: if optional: return '' else: error = "Environment variable '{ev}' not found.".format( ev=environment_variable) raise ImproperlyConfigured(error) SENTRY_ADDRESS = get_env_variable('SENTRY_ADDRESS', optional=True) if SENTRY_ADDRESS: sentry_sdk.init(dsn=SENTRY_ADDRESS, integrations=[DjangoIntegration()]) # Devlopment Environment Control DEBUG = 'DEBUG' in os.environ if 'DJANGO_HOST' in os.environ: DJANGO_HOST = get_env_variable("DJANGO_HOST") else: DJANGO_HOST = 'LOCALHOST' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = get_env_variable("DJANGO_SECRET_KEY") ALLOWED_HOSTS = [ ".herokuapp.com", ".civiwiki.org", "127.0.0.1", "localhost", "0.0.0.0" ]
https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import sys import json import stripe import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://[email protected]/1370205", integrations=[DjangoIntegration(transaction_style='url')], send_default_pii=True) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ "www.louisemisellinteriors.co.uk", "louisemisellinteriors.co.uk", "test.louisemisellinteriors.co.uk" ]
}, }, "loggers": { "django": { "level": "INFO", "handlers": ["console"], "propagate": False, }, "apps": { "level": "DEBUG", "handlers": ["console"], "propagate": False }, }, } USE_SENTRY = env.bool("USE_SENTRY", default=False) if USE_SENTRY: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init(dsn=env("SENTRY_DSN"), integrations=[DjangoIntegration()]) # ----------------------------------------------------------------------------- # Security # ----------------------------------------------------------------------------- SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = "DENY"
WEBPACK_LOADER = { "DEFAULT": { "BUNDLE_DIR_NAME": "bundles/", "STATS_FILE": os.path.join(BASE_DIR, "webpack-stats.json"), } } MESSAGE_STORAGE = "django.contrib.messages.storage.session.SessionStorage" # Sites SITE_ID = 1 # Sentry Error Tracking if not DEBUG: sentry_sdk.init(dsn=env("dsn"), integrations=[DjangoIntegration()]) EMAILOCTOPUS_API = env("EMAILOCTOPUS_API") OCTO_LIST_ID = env("OCTO_LIST_ID") INTERNAL_IPS = [ "127.0.0.1", ] AUTH_USER_MODEL = "users.CustomUser" DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # config/settings.py LOGIN_REDIRECT_URL = "home" ACCOUNT_LOGOUT_REDIRECT_URL = "home"
), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication', ) } UNICODE_JSON = True # The sentry DSN for error reporting SENTRY_DSN = os.environ.get('SENTRY_DSN') if IS_PRODUCTION: if not SENTRY_DSN: raise NameError( 'SENTRY_DSN environment variable is required when running on a production environment' ) sentry_sdk.init(dsn=SENTRY_DSN, integrations=[DjangoIntegration()]) else: if SENTRY_DSN: logger.info('SENTRY_DSN environment variable ignored.') # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ TIME_ZONE = 'Europe/Amsterdam' USE_I18N = True USE_L10N = True USE_TZ = True
STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATIC_URL = f"{os.path.join(AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)}/" STATIC_ROOT = "" else: # run collectstatic, check nginx LOCATION STATIC_URL = env.str("DJANGO_STATIC_URL") STATIC_ROOT = env.str("DJANGO_STATIC_ROOT") SENTRY_DSN = None if SENTRY_ENABLED: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn=SENTRY_DSN, integrations=[DjangoIntegration()], send_default_pii=True ) else: if env("DJANGO_LOGGING_ENABLED"): from .logging.standard import LOGGING # noqa # if SENTRY_ENABLED: # import raven # noqa # from .logging.raven import LOGGING # noqa # # SENTRY_DSN = env.str("SENTRY_DSN") # RAVEN_CONFIG = {"dsn": SENTRY_DSN, # "release": raven.fetch_git_sha(BASE_DIR)} # else: # if env("DJANGO_LOGGING_ENABLED"): # from .logging.standard import LOGGING # noqa
"level": "ERROR", "handlers": ["console"], "propagate": False }, "django.security.DisallowedHost": { "level": "ERROR", "handlers": ["console"], "propagate": False, }, }, } # Sentry # ------------------------------------------------------------------------------ SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=None, # Send no events from log messages ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) # Your stuff... # ------------------------------------------------------------------------------
# Senty DNS is taken from SENTRY_DSN environment variable # https://sentry.io/for/django/ # https://sentry.io/for/celery/ # https://docs.sentry.io/platforms/python/logging/ SENTRY_ENVIRONMENT = env("SENTRY_ENVIRONMENT", default="production") # https://docs.sentry.io/workflow/releases/?platform=python SENTRY_RELEASE = f"build_migration@{APP_VERSION}" sentry_sdk.init( release=SENTRY_RELEASE, environment=SENTRY_ENVIRONMENT, integrations=[ # fmt: off DjangoIntegration(), # fmt: off ], # fmt: off ) # SECURITY # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#secure-proxy-ssl-header SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # https://docs.djangoproject.com/en/dev/ref/settings/#secure-ssl-redirect SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True) # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-secure SESSION_COOKIE_SECURE = True # https://docs.djangoproject.com/en/dev/ref/settings/#session-cookie-httponly SESSION_COOKIE_HTTPONLY = True # https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-secure
import os from pathlib import Path from dynaconf import settings as _ds import dj_database_url import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://[email protected]/5477460", integrations=[DjangoIntegration()], 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 ) REPO_DIR = Path(__file__).resolve().parent.parent.parent BASE_DIR = REPO_DIR / "src" PROJECT_DIR = BASE_DIR / "project" SECRET_KEY = _ds.SECRET_KEY # SECURITY WARNING: don't run with debug turned on in production! DEBUG = _ds.DEBUG ALLOWED_HOSTS = _ds.ALLOWED_HOSTS + ['noway2codenoramal.herokuapp.com', "localhost", "127.0.0.1", ]
# e.g. HTTP_CF_Connecting_IP for Cloudflare or X_FORWARDED_FOR REAL_IP_ENVIRON = os.environ.get("REAL_IP_ENVIRON", "REMOTE_ADDR") # Slugs for menus precreated in Django migrations DEFAULT_MENUS = {"top_menu_name": "navbar", "bottom_menu_name": "footer"} # Slug for channel precreated in Django migrations DEFAULT_CHANNEL_SLUG = os.environ.get("DEFAULT_CHANNEL_SLUG", "default-channel") # Sentry sentry_sdk.utils.MAX_STRING_LENGTH = 4096 SENTRY_DSN = os.environ.get("SENTRY_DSN") if SENTRY_DSN: sentry_sdk.init( dsn=SENTRY_DSN, integrations=[CeleryIntegration(), DjangoIntegration()] ) ignore_logger("graphql.execution.utils") GRAPHENE = { "RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST": True, "RELAY_CONNECTION_MAX_LIMIT": 100, "MIDDLEWARE": [ "saleor.graphql.middleware.OpentracingGrapheneMiddleware", "saleor.graphql.middleware.JWTMiddleware", "saleor.graphql.middleware.app_middleware", ], } PLUGINS = [ "saleor.plugins.avatax.plugin.AvataxPlugin",
# See https://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { "version": 1, "disable_existing_loggers": True, "formatters": {"verbose": {"format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s"}}, "handlers": {"console": {"level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose",}}, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { "django.db.backends": {"level": "ERROR", "handlers": ["console"], "propagate": False,}, # Errors logged by the SDK itself "sentry_sdk": {"level": "ERROR", "handlers": ["console"], "propagate": False}, "django.security.DisallowedHost": {"level": "ERROR", "handlers": ["console"], "propagate": False,}, }, } # Sentry # ------------------------------------------------------------------------------ SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, event_level=logging.ERROR, # Capture info and above as breadcrumbs # Send errors as events ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) # Your stuff... # ------------------------------------------------------------------------------
INTERNAL_IPS = os.getenv('INTERNAL_IPS', '').split() EMAIL_BACKEND = os.getenv( 'EMAIL_BACKEND', 'django.core.mail.backends.smtp.EmailBackend' ) PODCAST_AD_ID = os.getenv('PODCAST_AD_ID') MAX_EPISODE_ACTIONS = int(os.getenv('MAX_EPISODE_ACTIONS', 1000)) SEARCH_CUTOFF = float(os.getenv('SEARCH_CUTOFF', 0.3)) ### Sentry try: import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration # Sentry Data Source Name (DSN) sentry_dsn = os.getenv('SENTRY_DSN', '') if not sentry_dsn: raise ValueError('Could not set up sentry because ' 'SENTRY_DSN is not set') sentry_sdk.init(dsn=sentry_dsn, integrations=[DjangoIntegration()]) except (ImportError, ValueError): pass