@@ -22,10 +22,10 @@ def timed_with_status(
2222 Parameters:
2323 - log: enable timing logs (default True)
2424 - log_prefix: prefix; falls back to function name
25- - log_args: names to include in logs (str or list/tuple of str).
26- - log_extra_args: extra arguments to include in logs (dict). If it contains
27- key "time_threshold", use its value (in seconds) as the logging threshold; otherwise
28- fall back to DEFAULT_TIME_BAR .
25+ - log_args: names to include in logs (str or list/tuple of str), values are taken from kwargs by name .
26+ - log_extra_args:
27+ - can be a dict: fixed contextual fields that are always attached to logs;
28+ - or a callable: like `fn(*args, **kwargs) -> dict`, used to dynamically generate contextual fields at runtime .
2929 """
3030
3131 if isinstance (log_args , str ):
@@ -56,12 +56,24 @@ def wrapper(*args, **kwargs):
5656 elapsed_ms = (time .perf_counter () - start ) * 1000.0
5757
5858 ctx_parts = []
59+ # 1) Collect parameters from kwargs by name
5960 for key in effective_log_args :
6061 val = kwargs .get (key )
6162 ctx_parts .append (f"{ key } ={ val } " )
6263
63- if log_extra_args :
64- ctx_parts .extend (f"{ key } ={ val } " for key , val in log_extra_args .items ())
64+ # 2) Support log_extra_args as dict or callable, so we can dynamically
65+ # extract values from self or other runtime context
66+ extra_items = {}
67+ try :
68+ if callable (log_extra_args ):
69+ extra_items = log_extra_args (* args , ** kwargs ) or {}
70+ elif isinstance (log_extra_args , dict ):
71+ extra_items = log_extra_args
72+ except Exception as e :
73+ logger .warning (f"[TIMER_WITH_STATUS] log_extra_args callback error: { e !r} " )
74+
75+ if extra_items :
76+ ctx_parts .extend (f"{ key } ={ val } " for key , val in extra_items .items ())
6577
6678 ctx_str = f" [{ ', ' .join (ctx_parts )} ]" if ctx_parts else ""
6779
@@ -75,15 +87,8 @@ def wrapper(*args, **kwargs):
7587 f"[TIMER_WITH_STATUS] { log_prefix or fn .__name__ } "
7688 f"took { elapsed_ms :.0f} ms{ status_info } , args: { ctx_str } "
7789 )
78- threshold_ms = DEFAULT_TIME_BAR * 1000.0
79- if log_extra_args and "time_threshold" in log_extra_args :
80- try :
81- threshold_ms = float (log_extra_args ["time_threshold" ]) * 1000.0
82- except Exception :
83- threshold_ms = DEFAULT_TIME_BAR * 1000.0
8490
85- if elapsed_ms >= threshold_ms :
86- logger .info (msg )
91+ logger .info (msg )
8792
8893 return wrapper
8994
@@ -92,7 +97,7 @@ def wrapper(*args, **kwargs):
9297 return decorator (func )
9398
9499
95- def timed (func = None , * , log = True , log_prefix = "" ):
100+ def timed (func = None , * , log = False , log_prefix = "" ):
96101 def decorator (fn ):
97102 def wrapper (* args , ** kwargs ):
98103 start = time .perf_counter ()
0 commit comments