-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtracking.py
More file actions
49 lines (40 loc) · 1.56 KB
/
tracking.py
File metadata and controls
49 lines (40 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import types
import uuid
from debug_toolbar.utils import get_stack_trace
from django_mongodb_backend.utils import OperationDebugWrapper
from pymongo.collection import Collection
def patch_get_collection(connection):
"""
Patch the get_collection method of the connection to return a wrapped
Collection object that logs queries for the debug toolbar.
"""
def get_collection(self, name, **kwargs):
return DebugToolbarWrapper(
self, Collection(self.database, name, **kwargs), connection._djdt_logger
)
connection.get_collection = types.MethodType(get_collection, connection)
class DebugToolbarWrapper(OperationDebugWrapper):
"""
A wrapper around pymongo Collection objects that logs queries for the
debug toolbar.
"""
def __init__(self, db, collection, logger):
super().__init__(db, collection)
self.logger = logger
def log(self, op, duration, args, kwargs=None):
args = ", ".join(repr(arg) for arg in args)
operation = f"db.{self.collection_name}{op}({args})"
if self.logger:
self.logger._sql_time += duration
self.logger._queries.append(
{
"alias": self.db.alias,
"sql": operation,
"duration": "%.3f" % duration,
"djdt_query_id": uuid.uuid4().hex,
"stacktrace": get_stack_trace(),
}
)
self.logger._databases[self.db.alias] = {
"num_queries": len(self.logger._queries),
}