Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Setup structlog Sentry integration (#4704)

Olga Bulat3cd0aca88981
diff --git a/api/api/admin/media_report.py b/api/api/admin/media_report.py
index 5114d3344..045966a18 100644
--- a/api/api/admin/media_report.py
+++ b/api/api/admin/media_report.py
@@ -489,7 +489,7 @@ class MediaListAdmin(BulkModerationMixin, admin.ModelAdmin):
if search.hits:
return False
except NotFoundError:
- logger.error("Could not resolve index.", name=filtered_index)
+ logger.error("Could not resolve index.", name=filtered_index, exc_info=True)
return True
#############
diff --git a/api/api/utils/aiohttp.py b/api/api/utils/aiohttp.py
index 2724953c4..c3dacf1ba 100644
--- a/api/api/utils/aiohttp.py
+++ b/api/api/utils/aiohttp.py
@@ -3,7 +3,6 @@ import time
import weakref
import aiohttp
-import sentry_sdk
import structlog
from django_asgi_lifespan.signals import asgi_shutdown
@@ -32,8 +31,7 @@ async def _close_sessions(sender, **kwargs):
await session.close()
closed_sessions += 1
except BaseException as exc:
- logger.error(exc)
- sentry_sdk.capture_exception(exc)
+ logger.error("Error closing sessions", exc=exc, exc_info=True)
logger.debug("Successfully closed %s session(s)", closed_sessions)
diff --git a/api/api/utils/image_proxy/extension.py b/api/api/utils/image_proxy/extension.py
index 07d4ffe59..876922a2f 100644
--- a/api/api/utils/image_proxy/extension.py
+++ b/api/api/utils/image_proxy/extension.py
@@ -6,7 +6,6 @@ from django.conf import settings
import aiohttp
import django_redis
-import sentry_sdk
import structlog
from asgiref.sync import sync_to_async
from redis.exceptions import ConnectionError
@@ -60,7 +59,7 @@ async def get_image_extension(media_info: MediaInfo) -> str | None:
await _cache_extension(cache, key, ext)
except Exception as exc:
- sentry_sdk.capture_exception(exc)
+ logger.error("upstream_thumbnail_exception", exc=exc, exc_info=True)
raise UpstreamThumbnailException(
"Failed to render thumbnail due to inability to check media "
f"type. {exc}"
diff --git a/api/api/utils/watermark.py b/api/api/utils/watermark.py
index 7a77a2be0..fbad4fe35 100644
--- a/api/api/utils/watermark.py
+++ b/api/api/utils/watermark.py
@@ -11,7 +11,6 @@ import requests
import structlog
from openverse_attribution.license import License
from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError
-from sentry_sdk import capture_exception
logger = structlog.get_logger(__name__)
@@ -153,12 +152,10 @@ def _open_image(url):
img_bytes = BytesIO(response.content)
img = Image.open(img_bytes)
except requests.exceptions.RequestException as e:
- capture_exception(e)
- logger.error(f"Error requesting image: {e}")
+ logger.error("Error requesting image", exc=e, exc_info=True)
raise UpstreamWatermarkException(f"{e}")
except UnidentifiedImageError as e:
- capture_exception(e)
- logger.error(f"Error loading image data: {e}")
+ logger.error("Error loading image data", exc=e, exc_info=True)
raise UpstreamWatermarkException(f"{e}")
return img, img.getexif()
diff --git a/api/api/utils/waveform.py b/api/api/utils/waveform.py
index fbc8ffe5d..57329841c 100644
--- a/api/api/utils/waveform.py
+++ b/api/api/utils/waveform.py
@@ -11,7 +11,6 @@ from rest_framework import status
from rest_framework.exceptions import APIException
import requests
-import sentry_sdk
import structlog
@@ -79,11 +78,10 @@ def download_audio(url, identifier):
with open(TMP_DIR.joinpath(file_name), "wb") as file:
shutil.copyfileobj(res.raw, file)
except (requests.RequestException, ValueError) as e:
- logger.error("waveform_audio_download_failed", e=e)
+ logger.error("waveform_audio_download_failed", exc=e, exc_info=True)
if isinstance(e, requests.RequestException):
raise UpstreamWaveformException()
else:
- sentry_sdk.capture_exception(e)
raise WaveformGenerationFailure("Unknown file extension")
return file_name
@@ -126,8 +124,9 @@ def generate_waveform(file_name: str, duration: int):
try:
proc = subprocess.run(args, cwd=TMP_DIR, check=True, capture_output=True)
except subprocess.CalledProcessError as e:
- logger.error("waveform_generation_failed", file_name=file_name, e=e)
- sentry_sdk.capture_exception(e)
+ logger.error(
+ "waveform_generation_failed", file_name=file_name, exc=e, exc_info=True
+ )
# Do not return details of the exception; we're calling directly to a system binary, and
# the command output could be sensitive. Folks debugging can find details in the logs
raise WaveformGenerationFailure()
@@ -186,8 +185,9 @@ def cleanup(file_name):
os.remove(file_path)
except (OSError, FileNotFoundError) as e:
# Do not raise a further exception, because this actually doesn't necessarily mean the request needs to fail
- sentry_sdk.capture_exception(e)
- logger.error("waveform_cleanup_failed", e=e, file_name=file_name)
+ logger.error(
+ "waveform_cleanup_failed", exc=e, file_name=file_name, exc_info=True
+ )
return
logger.debug("file deleted")
diff --git a/api/api/views/oauth2_views.py b/api/api/views/oauth2_views.py
index be29390cb..3a886eb78 100644
--- a/api/api/views/oauth2_views.py
+++ b/api/api/views/oauth2_views.py
@@ -109,8 +109,7 @@ class Register(APIView):
fail_silently=False,
)
except smtplib.SMTPException as e:
- logger.error("Failed to send API verification email!")
- logger.error(e)
+ logger.error("Failed to send API verification email!", exc=e, exc_info=True)
# Give the user their newly created credentials.
return Response(
status=201,
diff --git a/api/conf/settings/logging.py b/api/conf/settings/logging.py
index 26b4e43ff..0e1b598a6 100644
--- a/api/conf/settings/logging.py
+++ b/api/conf/settings/logging.py
@@ -1,7 +1,9 @@
+import logging
from logging import LogRecord
import structlog
from decouple import config
+from structlog_sentry import SentryProcessor
from conf.settings.base import ENVIRONMENT, INSTALLED_APPS, MIDDLEWARE
from conf.settings.security import DEBUG
@@ -49,6 +51,17 @@ shared_processors = [
}
),
structlog.processors.StackInfoRenderer(),
+ # https://github.com/kiwicom/structlog-sentry - for Sentry integration
+ # Must go after `add_logger_name` and `add_log_level`,
+ # but before `format_exc_info`
+ SentryProcessor(
+ event_level=logging.ERROR,
+ # `level` here dictates which log levels will be included in breadcrumbs
+ # Set to WARNING for now to prevent PII/sensitive info from appearing there
+ level=logging.WARNING,
+ # Also ignore any Django SQL logs entirely in case they get enabled
+ ignore_loggers=["django.db.backends"],
+ ),
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
]
diff --git a/api/conf/settings/sentry.py b/api/conf/settings/sentry.py
index 428eb6dee..cf109fbc1 100644
--- a/api/conf/settings/sentry.py
+++ b/api/conf/settings/sentry.py
@@ -1,7 +1,7 @@
import sentry_sdk
from decouple import config
from sentry_sdk.integrations.django import DjangoIntegration
-from sentry_sdk.integrations.logging import ignore_logger
+from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger
from conf.settings.base import ENVIRONMENT
@@ -12,10 +12,20 @@ SENTRY_SAMPLE_RATE = config("SENTRY_SAMPLE_RATE", default=1.0, cast=float)
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DJANGO_DEBUG_ENABLED", default=False, cast=bool)
+
+INTEGRATIONS = [
+ DjangoIntegration(),
+ # This prevents two errors from being sent to Sentry (one with the correct
+ # information and the other with the logged JSON as the error name), since we
+ # use JSON-logging as well which can conflict with the way Sentry expects alerts.
+ # https://github.com/kiwicom/structlog-sentry?tab=readme-ov-file#logging-as-json
+ LoggingIntegration(event_level=None, level=None),
+]
+
if not DEBUG and SENTRY_DSN:
sentry_sdk.init(
dsn=SENTRY_DSN,
- integrations=[DjangoIntegration()],
+ integrations=INTEGRATIONS,
traces_sample_rate=SENTRY_SAMPLE_RATE,
send_default_pii=False,
environment=ENVIRONMENT,
diff --git a/api/pdm.lock b/api/pdm.lock
index 1999fc355..4d439a208 100644
--- a/api/pdm.lock
+++ b/api/pdm.lock
@@ -5,7 +5,7 @@
groups = ["default", "dev", "overrides", "test"]
strategy = ["inherit_metadata"]
lock_version = "4.5.0"
-content_hash = "sha256:b5b54c06235e8a363db385bb12af39fecc3048d46969c7ece1a41b022e24e7b9"
+content_hash = "sha256:56b7ee9bb04cad671dd572c9e57b807fa3e3abb4fdf8233665bdc952b9b5a1d1"
[[metadata.targets]]
requires_python = "==3.11.*"
@@ -1905,6 +1905,21 @@ files = [
{file = "structlog-24.1.0.tar.gz", hash = "sha256:41a09886e4d55df25bdcb9b5c9674bccfab723ff43e0a86a1b7b236be8e57b16"},
]
+[[package]]
+name = "structlog-sentry"
+version = "2.1.0"
+requires_python = ">=3.7,<4.0"
+summary = "Sentry integration for structlog"
+groups = ["default"]
+dependencies = [
+ "sentry-sdk",
+ "structlog",
+]
+files = [
+ {file = "structlog_sentry-2.1.0-py3-none-any.whl", hash = "sha256:8f631fc4cf9890f8ea368f057861b62ceef30dd75726a85706869807926e22d0"},
+ {file = "structlog_sentry-2.1.0.tar.gz", hash = "sha256:ee4fb04a381f25570017dd26345ea15b6461cbf87ae0a315e20ddd822ad4256b"},
+]
+
[[package]]
name = "tabulate"
version = "0.9.0"
diff --git a/api/pyproject.toml b/api/pyproject.toml
index eb78058a9..63b6d43e3 100644
--- a/api/pyproject.toml
+++ b/api/pyproject.toml
@@ -37,6 +37,7 @@ dependencies = [
"sentry-sdk >=1.40.6, <2",
"uvicorn[standard] >=0.30, <0.31",
"openverse-attribution @ file:///${PROJECT_ROOT}/../packages/python/openverse-attribution",
+ "structlog-sentry>=2.1.0",
]
[tool.pdm]