plainx-sentry 0.4.0__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plainx-sentry
3
- Version: 0.4.0
3
+ Version: 0.4.1
4
4
  Author-email: Dave Gaeddert <dave.gaeddert@gmail.com>
5
5
  Requires-Python: >=3.11
6
6
  Requires-Dist: sentry-sdk>=2.24.0
@@ -0,0 +1,154 @@
1
+ import sentry_sdk
2
+ from plain.runtime import settings
3
+ from sentry_sdk.tracing import TransactionSource
4
+ from sentry_sdk.utils import capture_internal_exceptions
5
+
6
+ try:
7
+ from plain.models.db import connection
8
+ except ImportError:
9
+ connection = None
10
+
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def trace_db(execute, sql, params, many, context):
17
+ with sentry_sdk.start_span(op="db", description=sql) as span:
18
+ # Mostly borrowed from the Sentry Django integration...
19
+ data = {
20
+ "db.params": params,
21
+ "db.executemany": many,
22
+ "db.system": connection.vendor,
23
+ "db.name": connection.settings_dict.get("NAME"),
24
+ "db.user": connection.settings_dict.get("USER"),
25
+ "server.address": connection.settings_dict.get("HOST"),
26
+ "server.port": connection.settings_dict.get("PORT"),
27
+ }
28
+
29
+ sentry_sdk.add_breadcrumb(message=sql, category="query", data=data)
30
+
31
+ for k, v in data.items():
32
+ span.set_data(k, v)
33
+
34
+ result = execute(sql, params, many, context)
35
+
36
+ return result
37
+
38
+
39
+ class SentryMiddleware:
40
+ def __init__(self, get_response):
41
+ self.get_response = get_response
42
+
43
+ def __call__(self, request):
44
+ # Don't do anything if Sentry is not active
45
+ if not sentry_sdk.get_client().is_active():
46
+ return self.get_response(request)
47
+
48
+ def event_processor(event, hint):
49
+ # request gets attached directly to an event,
50
+ # not necessarily in the "context"
51
+ request_info = event.setdefault("request", {})
52
+ request_info["url"] = request.build_absolute_uri()
53
+ request_info["method"] = request.method
54
+ request_info["query_string"] = request.META.get("QUERY_STRING", "")
55
+ # Headers and env need some PII filtering, ideally,
56
+ # among other filters... similar for GET/POST data?
57
+ # request_info["headers"] = dict(request.headers)
58
+ try:
59
+ request_info["data"] = request.body.decode("utf-8")
60
+ except Exception:
61
+ pass
62
+
63
+ if user := getattr(request, "user", None):
64
+ event["user"] = {"id": str(user.pk)}
65
+ if settings.SENTRY_PII_ENABLED:
66
+ if email := getattr(user, "email", None):
67
+ event["user"]["email"] = email
68
+ if username := getattr(user, "username", None):
69
+ event["user"]["username"] = username
70
+
71
+ return event
72
+
73
+ with sentry_sdk.isolation_scope() as scope:
74
+ # Reset the scope (and breadcrumbs) for each request
75
+ scope.clear()
76
+ scope.add_event_processor(event_processor)
77
+
78
+ # Sentry's Django integration patches the WSGIHandler.
79
+ # We could make our own WSGIHandler and patch it or call it directly from gunicorn,
80
+ # but putting our middleware at the top of MIDDLEWARE is pretty close and easier.
81
+ with sentry_sdk.start_transaction(
82
+ op="http.server", name=request.path_info
83
+ ) as transaction:
84
+ if connection:
85
+ # Also get spans for db queries
86
+ with connection.execute_wrapper(trace_db):
87
+ response = self.get_response(request)
88
+ else:
89
+ # No db presumably
90
+ response = self.get_response(request)
91
+
92
+ if resolver_match := getattr(request, "resolver_match", None):
93
+ # Rename the transaction using a pattern,
94
+ # and attach other url/views tags we can use to filter
95
+ transaction.name = f"route:{resolver_match.route}"
96
+ transaction.set_tag("url_namespace", resolver_match.namespace)
97
+ transaction.set_tag("url_name", resolver_match.url_name)
98
+ transaction.set_tag("view_name", resolver_match.view_name)
99
+ transaction.set_tag("view_class", resolver_match._func_path)
100
+ # Don't need to filter on this, but do want the context to view
101
+ transaction.set_context(
102
+ "url_params",
103
+ {
104
+ "args": resolver_match.args,
105
+ "kwargs": resolver_match.kwargs,
106
+ },
107
+ )
108
+
109
+ transaction.set_http_status(response.status_code)
110
+
111
+ return response
112
+
113
+
114
+ class SentryWorkerMiddleware:
115
+ def __init__(self, run_job):
116
+ self.run_job = run_job
117
+
118
+ def __call__(self, job):
119
+ # Don't do anything if Sentry is not active
120
+ if not sentry_sdk.get_client().is_active():
121
+ return self.run_job(job)
122
+
123
+ def event_processor(event, hint):
124
+ with capture_internal_exceptions():
125
+ # Attach it directly to any events
126
+ extra = event.setdefault("extra", {})
127
+ extra["plain.worker"] = {"job": job.as_json()}
128
+ return event
129
+
130
+ with sentry_sdk.isolation_scope() as scope:
131
+ # Reset the scope (and breadcrumbs) for each request
132
+ scope.clear()
133
+ scope.add_event_processor(event_processor)
134
+
135
+ with sentry_sdk.start_transaction(
136
+ op="plain.worker.job",
137
+ name=f"job:{job.job_class}",
138
+ source=TransactionSource.TASK,
139
+ ) as transaction:
140
+ if connection:
141
+ # Also get spans for db queries
142
+ with connection.execute_wrapper(trace_db):
143
+ job_result = self.run_job(job)
144
+ else:
145
+ # No db presumably
146
+ job_result = self.run_job(job)
147
+
148
+ with capture_internal_exceptions():
149
+ # Don't need to filter on this, but do want the context to view
150
+ transaction.set_context("job", job.as_json())
151
+
152
+ transaction.set_status("ok")
153
+
154
+ return job_result
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "plainx-sentry"
3
- version = "0.4.0"
3
+ version = "0.4.1"
4
4
  description = ""
5
5
  readme = "README.md"
6
6
  authors = [
@@ -1,144 +0,0 @@
1
- import sentry_sdk
2
- from plain.runtime import settings
3
- from sentry_sdk.tracing import TransactionSource
4
- from sentry_sdk.utils import capture_internal_exceptions
5
-
6
- try:
7
- from plain.models.db import connection
8
- except ImportError:
9
- connection = None
10
-
11
- import logging
12
-
13
- logger = logging.getLogger(__name__)
14
-
15
-
16
- def trace_db(execute, sql, params, many, context):
17
- with sentry_sdk.start_span(op="db", description=sql) as span:
18
- # Mostly borrowed from the Sentry Django integration...
19
- data = {
20
- "db.params": params,
21
- "db.executemany": many,
22
- "db.system": connection.vendor,
23
- "db.name": connection.settings_dict.get("NAME"),
24
- "db.user": connection.settings_dict.get("USER"),
25
- "server.address": connection.settings_dict.get("HOST"),
26
- "server.port": connection.settings_dict.get("PORT"),
27
- }
28
-
29
- sentry_sdk.add_breadcrumb(message=sql, category="query", data=data)
30
-
31
- for k, v in data.items():
32
- span.set_data(k, v)
33
-
34
- result = execute(sql, params, many, context)
35
-
36
- return result
37
-
38
-
39
- class SentryMiddleware:
40
- def __init__(self, get_response):
41
- self.get_response = get_response
42
-
43
- def __call__(self, request):
44
- def event_processor(event, hint):
45
- # request gets attached directly to an event,
46
- # not necessarily in the "context"
47
- request_info = event.setdefault("request", {})
48
- request_info["url"] = request.build_absolute_uri()
49
- request_info["method"] = request.method
50
- request_info["query_string"] = request.META.get("QUERY_STRING", "")
51
- # Headers and env need some PII filtering, ideally,
52
- # among other filters... similar for GET/POST data?
53
- # request_info["headers"] = dict(request.headers)
54
- try:
55
- request_info["data"] = request.body.decode("utf-8")
56
- except Exception:
57
- pass
58
-
59
- if user := getattr(request, "user", None):
60
- event["user"] = {"id": str(user.pk)}
61
- if settings.SENTRY_PII_ENABLED:
62
- if email := getattr(user, "email", None):
63
- event["user"]["email"] = email
64
- if username := getattr(user, "username", None):
65
- event["user"]["username"] = username
66
-
67
- return event
68
-
69
- # Reset the scope (and breadcrumbs) for each request
70
- scope = sentry_sdk.get_isolation_scope()
71
- scope.add_event_processor(event_processor)
72
-
73
- # Sentry's Django integration patches the WSGIHandler.
74
- # We could make our own WSGIHandler and patch it or call it directly from gunicorn,
75
- # but putting our middleware at the top of MIDDLEWARE is pretty close and easier.
76
- with sentry_sdk.start_transaction(
77
- op="http.server", name=request.path_info
78
- ) as transaction:
79
- if connection:
80
- # Also get spans for db queries
81
- with connection.execute_wrapper(trace_db):
82
- response = self.get_response(request)
83
- else:
84
- # No db presumably
85
- response = self.get_response(request)
86
-
87
- if resolver_match := getattr(request, "resolver_match", None):
88
- # Rename the transaction using a pattern,
89
- # and attach other url/views tags we can use to filter
90
- transaction.name = f"route:{resolver_match.route}"
91
- transaction.set_tag("url_namespace", resolver_match.namespace)
92
- transaction.set_tag("url_name", resolver_match.url_name)
93
- transaction.set_tag("view_name", resolver_match.view_name)
94
- transaction.set_tag("view_class", resolver_match._func_path)
95
- # Don't need to filter on this, but do want the context to view
96
- transaction.set_context(
97
- "url_params",
98
- {
99
- "args": resolver_match.args,
100
- "kwargs": resolver_match.kwargs,
101
- },
102
- )
103
-
104
- transaction.set_http_status(response.status_code)
105
-
106
- return response
107
-
108
-
109
- class SentryWorkerMiddleware:
110
- def __init__(self, run_job):
111
- self.run_job = run_job
112
-
113
- def __call__(self, job):
114
- def event_processor(event, hint):
115
- with capture_internal_exceptions():
116
- # Attach it directly to any events
117
- extra = event.setdefault("extra", {})
118
- extra["plain.worker"] = {"job": job.as_json()}
119
- return event
120
-
121
- # Reset the scope (and breadcrumbs) for each job
122
- scope = sentry_sdk.get_isolation_scope()
123
- scope.add_event_processor(event_processor)
124
-
125
- with sentry_sdk.start_transaction(
126
- op="plain.worker.job",
127
- name=f"job:{job.job_class}",
128
- source=TransactionSource.TASK,
129
- ) as transaction:
130
- if connection:
131
- # Also get spans for db queries
132
- with connection.execute_wrapper(trace_db):
133
- job_result = self.run_job(job)
134
- else:
135
- # No db presumably
136
- job_result = self.run_job(job)
137
-
138
- with capture_internal_exceptions():
139
- # Don't need to filter on this, but do want the context to view
140
- transaction.set_context("job", job.as_json())
141
-
142
- transaction.set_status("ok")
143
-
144
- return job_result
File without changes
File without changes
File without changes