1
+ from typing import Union
2
+
3
+ from opentelemetry .trace .span import Span
4
+
1
5
from lumigo_opentelemetry .instrumentations import AbstractInstrumentor
6
+ from lumigo_opentelemetry import logger
7
+ from lumigo_opentelemetry .libs .general_utils import lumigo_safe_execute
8
+ from lumigo_opentelemetry .libs .json_utils import dump_with_context
2
9
3
10
4
11
class PymongoInstrumentor (AbstractInstrumentor ):
@@ -10,8 +17,43 @@ def check_if_applicable(self) -> None:
10
17
11
18
def install_instrumentation (self ) -> None :
12
19
from opentelemetry .instrumentation .pymongo import PymongoInstrumentor
20
+ from pymongo .monitoring import (
21
+ CommandStartedEvent ,
22
+ CommandSucceededEvent ,
23
+ CommandFailedEvent ,
24
+ )
25
+
26
+ def request_hook (span : Span , event : CommandStartedEvent ) -> None :
27
+ with lumigo_safe_execute ("pymongo_request_hook" ):
28
+ span .set_attribute ("db.statement" , event .command_name )
29
+ if isinstance (event , CommandStartedEvent ):
30
+ span .set_attribute (
31
+ "db.request.body" ,
32
+ dump_with_context ("requestBody" , event .command ),
33
+ )
34
+ else :
35
+ logger .warning (f"Got unexpected event type { type (event )} " )
36
+
37
+ def response_hook (
38
+ span : Span , event : Union [CommandSucceededEvent , CommandFailedEvent ]
39
+ ) -> None :
40
+ with lumigo_safe_execute ("pymongo_response_hook" ):
41
+ if isinstance (event , CommandSucceededEvent ):
42
+ span .set_attribute (
43
+ "db.response.body" ,
44
+ dump_with_context ("responseBody" , event .reply ),
45
+ )
46
+ elif isinstance (event , CommandFailedEvent ):
47
+ span .set_attribute (
48
+ "db.response.body" ,
49
+ dump_with_context ("responseBody" , event .failure ),
50
+ )
51
+ else :
52
+ logger .warning (f"Got unexpected event type { type (event )} " )
13
53
14
- PymongoInstrumentor ().instrument ()
54
+ PymongoInstrumentor ().instrument (
55
+ request_hook = request_hook , response_hook = response_hook
56
+ )
15
57
16
58
17
59
instrumentor : AbstractInstrumentor = PymongoInstrumentor ()
0 commit comments