1616__global_context_var : ContextVar [dict [str , Any ]] = ContextVar (
1717 "global_context" , default = {}
1818)
19+ __global_context_initialized : ContextVar [bool ] = ContextVar (
20+ "global_context_initialized" , default = False
21+ )
1922
2023
2124def _get_loggers_to_process (loggers : Optional [Sequence [Logger ]] = None ) -> list [Logger ]:
@@ -30,6 +33,7 @@ def init_global_context(loggers: Optional[Sequence[Logger]] = None) -> None:
3033 loggers: The loggers to attach the global context; if not loggers are specified
3134 it will use the root logger.
3235 """
36+ __global_context_initialized .set (True )
3337 filter_with_context = FilterWithContextVar (__global_context_var )
3438 for logger in _get_loggers_to_process (loggers ):
3539 for handler in logger .handlers :
@@ -44,6 +48,7 @@ def shutdown_global_context(loggers: Optional[Sequence[Logger]] = None) -> None:
4448 loggers: The loggers that were used when calling `init_global_context`; by
4549 default the root logger.
4650 """
51+ __global_context_initialized .set (False )
4752 for logger in _get_loggers_to_process (loggers ):
4853 for handler in logger .handlers :
4954 for filter_ in handler .filters :
@@ -74,20 +79,36 @@ def global_context_initialized(
7479
7580
7681@contextmanager
77- def add_global_context (context : dict [str , Any ]) -> Generator [None , None , None ]:
82+ def add_global_context (
83+ context : dict [str , Any ], * , auto_init : bool = True
84+ ) -> Generator [None , None , None ]:
7885 """
7986 Add values to the global context to be attached to all the log messages.
8087
8188 The values will be removed from the global context once the context manager exists.
8289
8390 Parameters:
8491 context: A key/value mapping with the values to add to the global context.
92+ auto_init: Indicate if the global context should be automatically initialized
93+ if it isn't.
94+
95+ If `True`, the context will be also automatically shutdown before exiting.
96+
97+ If the global context is already initialized it'll do nothing.
98+
99+ Keyword-only argument.
85100
86101 Returns:
87102 A context manager that manages the life of the values.
88103 """
104+ auto_initialized = False
105+ if not __global_context_initialized .get () and auto_init :
106+ init_global_context ()
107+ auto_initialized = True
89108 token = __global_context_var .set (__global_context_var .get () | context )
90109 try :
91110 yield
92111 finally :
93112 __global_context_var .reset (token )
113+ if auto_initialized :
114+ shutdown_global_context ()
0 commit comments