1
- from functools import wraps
2
1
import sys
3
2
4
- from sentry_sdk ._compat import reraise
3
+ from sentry_sdk ._compat import contextmanager , reraise
5
4
from sentry_sdk ._types import TYPE_CHECKING
6
5
from sentry_sdk .crons import capture_checkin
7
6
from sentry_sdk .crons .consts import MonitorStatus
8
7
from sentry_sdk .utils import now
9
8
10
-
11
9
if TYPE_CHECKING :
12
- from typing import Any , Callable , Optional
10
+ from typing import Generator , Optional
13
11
14
12
13
+ @contextmanager
15
14
def monitor (monitor_slug = None ):
16
- # type: (Optional[str]) -> Callable[..., Any ]
15
+ # type: (Optional[str]) -> Generator[None, None, None ]
17
16
"""
18
- Decorator to capture checkin events for a monitor.
17
+ Decorator/context manager to capture checkin events for a monitor.
19
18
20
- Usage:
19
+ Usage (as decorator) :
21
20
```
22
21
import sentry_sdk
23
22
@@ -31,44 +30,41 @@ def test(arg):
31
30
32
31
This does not have to be used with Celery, but if you do use it with celery,
33
32
put the `@sentry_sdk.monitor` decorator below Celery's `@app.task` decorator.
34
- """
35
-
36
- def decorate (func ):
37
- # type: (Callable[..., Any]) -> Callable[..., Any]
38
- if not monitor_slug :
39
- return func
40
33
41
- @wraps (func )
42
- def wrapper (* args , ** kwargs ):
43
- # type: (*Any, **Any) -> Any
44
- start_timestamp = now ()
45
- check_in_id = capture_checkin (
46
- monitor_slug = monitor_slug , status = MonitorStatus .IN_PROGRESS
47
- )
48
-
49
- try :
50
- result = func (* args , ** kwargs )
51
- except Exception :
52
- duration_s = now () - start_timestamp
53
- capture_checkin (
54
- monitor_slug = monitor_slug ,
55
- check_in_id = check_in_id ,
56
- status = MonitorStatus .ERROR ,
57
- duration = duration_s ,
58
- )
59
- exc_info = sys .exc_info ()
60
- reraise (* exc_info )
34
+ Usage (as context manager):
35
+ ```
36
+ import sentry_sdk
61
37
62
- duration_s = now () - start_timestamp
63
- capture_checkin (
64
- monitor_slug = monitor_slug ,
65
- check_in_id = check_in_id ,
66
- status = MonitorStatus .OK ,
67
- duration = duration_s ,
68
- )
38
+ def test(arg):
39
+ with sentry_sdk.monitor(monitor_slug='my-fancy-slug'):
40
+ print(arg)
41
+ ```
69
42
70
- return result
71
43
72
- return wrapper
44
+ """
73
45
74
- return decorate
46
+ start_timestamp = now ()
47
+ check_in_id = capture_checkin (
48
+ monitor_slug = monitor_slug , status = MonitorStatus .IN_PROGRESS
49
+ )
50
+
51
+ try :
52
+ yield
53
+ except Exception :
54
+ duration_s = now () - start_timestamp
55
+ capture_checkin (
56
+ monitor_slug = monitor_slug ,
57
+ check_in_id = check_in_id ,
58
+ status = MonitorStatus .ERROR ,
59
+ duration = duration_s ,
60
+ )
61
+ exc_info = sys .exc_info ()
62
+ reraise (* exc_info )
63
+
64
+ duration_s = now () - start_timestamp
65
+ capture_checkin (
66
+ monitor_slug = monitor_slug ,
67
+ check_in_id = check_in_id ,
68
+ status = MonitorStatus .OK ,
69
+ duration = duration_s ,
70
+ )
0 commit comments