2121
2222logger = logging .getLogger (__name__ )
2323
24+ lambda_stats = None
25+
2426
2527class StatsWriter :
2628 def distribution (self , metric_name , value , tags = [], timestamp = None ):
@@ -111,16 +113,17 @@ def stop(self):
111113 self .thread_stats .stop ()
112114
113115
114- lambda_stats = None
115- if should_use_extension :
116- lambda_stats = StatsDWriter ()
117- else :
118- # Periodical flushing in a background thread is NOT guaranteed to succeed
119- # and leads to data loss. When disabled, metrics are only flushed at the
120- # end of invocation. To make metrics submitted from a long-running Lambda
121- # function available sooner, consider using the Datadog Lambda extension.
122- flush_in_thread = os .environ .get ("DD_FLUSH_IN_THREAD" , "" ).lower () == "true"
123- lambda_stats = ThreadStatsWriter (flush_in_thread )
116+ def init_lambda_stats ():
117+ global lambda_stats
118+ if should_use_extension :
119+ lambda_stats = StatsDWriter ()
120+ else :
121+ # Periodical flushing in a background thread is NOT guaranteed to succeed
122+ # and leads to data loss. When disabled, metrics are only flushed at the
123+ # end of invocation. To make metrics submitted from a long-running Lambda
124+ # function available sooner, consider using the Datadog Lambda extension.
125+ flush_in_thread = os .environ .get ("DD_FLUSH_IN_THREAD" , "" ).lower () == "true"
126+ lambda_stats = ThreadStatsWriter (flush_in_thread )
124127
125128
126129def lambda_metric (metric_name , value , timestamp = None , tags = None , force_async = False ):
@@ -136,6 +139,7 @@ def lambda_metric(metric_name, value, timestamp=None, tags=None, force_async=Fal
136139 periodically and at the end of the function execution in a
137140 background thread.
138141 """
142+ global lambda_stats
139143 flush_to_logs = os .environ .get ("DD_FLUSH_TO_LOG" , "" ).lower () == "true"
140144 tags = tag_dd_lambda_layer (tags )
141145
@@ -164,6 +168,7 @@ def write_metric_point_to_stdout(metric_name, value, timestamp=None, tags=[]):
164168
165169
166170def flush_stats ():
171+ global lambda_stats
167172 lambda_stats .flush ()
168173
169174
0 commit comments