1919
2020from prometheus_client import Counter
2121
22- from synapse .logging .context import LoggingContext , current_context
22+ from synapse .logging .context import (
23+ ContextResourceUsage ,
24+ LoggingContext ,
25+ current_context ,
26+ )
2327from synapse .metrics import InFlightGauge
2428
2529logger = logging .getLogger (__name__ )
@@ -104,27 +108,27 @@ class Measure:
104108 def __init__ (self , clock , name ):
105109 self .clock = clock
106110 self .name = name
107- self ._logging_context = None
111+ parent_context = current_context ()
112+ self ._logging_context = LoggingContext (
113+ "Measure[%s]" % (self .name ,), parent_context
114+ )
108115 self .start = None
109116
110- def __enter__ (self ):
111- if self ._logging_context :
117+ def __enter__ (self ) -> "Measure" :
118+ if self .start is not None :
112119 raise RuntimeError ("Measure() objects cannot be re-used" )
113120
114121 self .start = self .clock .time ()
115- parent_context = current_context ()
116- self ._logging_context = LoggingContext (
117- "Measure[%s]" % (self .name ,), parent_context
118- )
119122 self ._logging_context .__enter__ ()
120123 in_flight .register ((self .name ,), self ._update_in_flight )
124+ return self
121125
122126 def __exit__ (self , exc_type , exc_val , exc_tb ):
123- if not self ._logging_context :
127+ if self .start is None :
124128 raise RuntimeError ("Measure() block exited without being entered" )
125129
126130 duration = self .clock .time () - self .start
127- usage = self ._logging_context . get_resource_usage ()
131+ usage = self .get_resource_usage ()
128132
129133 in_flight .unregister ((self .name ,), self ._update_in_flight )
130134 self ._logging_context .__exit__ (exc_type , exc_val , exc_tb )
@@ -140,6 +144,13 @@ def __exit__(self, exc_type, exc_val, exc_tb):
140144 except ValueError :
141145 logger .warning ("Failed to save metrics! Usage: %s" , usage )
142146
147+ def get_resource_usage (self ) -> ContextResourceUsage :
148+ """Get the resources used within this Measure block
149+
150+ If the Measure block is still active, returns the resource usage so far.
151+ """
152+ return self ._logging_context .get_resource_usage ()
153+
143154 def _update_in_flight (self , metrics ):
144155 """Gets called when processing in flight metrics
145156 """
0 commit comments