11import logging
22import os
3+ import threading
4+
35from google .cloud .logging .handlers import CloudLoggingHandler
46import google .cloud .logging
57from google .cloud .logging_v2 import Client
@@ -14,7 +16,7 @@ def get_env_logging_level():
1416def is_local_env ():
1517 return os .getenv ("K_SERVICE" ) is None
1618
17-
19+ lock = threading . Lock ()
1820class Logger :
1921 """
2022 GCP-friendly logger: structured JSON output, works locally or in production.
@@ -54,44 +56,32 @@ def init_logger():
5456 """
5557 Initializes the logger
5658 """
57- logging .basicConfig (level = get_env_logging_level ())
58- if is_local_env ():
59- # Use the default logging handler
60- logging .info ("Using default logging handler" )
61- return
62- try :
63- client = google .cloud .logging .Client ()
64- client .get_default_handler ()
65- client .setup_logging ()
66- logging .info ("GCP logging client initialized" )
67- # return client
68- except Exception as error :
69- # This might happen when the GCP authorization credentials are not available.
70- # Example, when running the tests locally
71- logging .error (f"Error initializing the logger: { error } " )
72- # return None
73-
74- # def setup_sqlalchemy_logger(self, handler):
75- # sqlalchemy_loggers = [
76- # "sqlalchemy.engine",
77- # # "sqlalchemy.pool",
78- # # "sqlalchemy.dialects.postgresql",
79- # "sqlalchemy.engine.Engine",
80- # ]
81- # for logger_name in sqlalchemy_loggers:
82- # logger = logging.getLogger(logger_name)
83- # logger.setLevel(get_env_logging_level())
84- # logger.handlers.clear()
85- # logger.addHandler(handler)
86- # logger.propagate = False
59+ with lock :
60+ if hasattr (Logger , "initialized" ):
61+ return
62+ logging .basicConfig (level = get_env_logging_level ())
63+ if not is_local_env ():
64+ # Use the default logging handler
65+ logging .info ("Using default logging handler" )
66+ return
67+ try :
68+ client = google .cloud .logging .Client ()
69+ client .get_default_handler ()
70+ client .setup_logging ()
71+ logging .info ("GCP logging client initialized" )
72+ except Exception as error :
73+ # This might happen when the GCP authorization credentials are not available.
74+ # Example, when running the tests locally
75+ logging .error (f"Error initializing the logger: { error } " )
76+ Logger .initialized = True
8777
8878 def get_logger (self ):
8979 return self .logger
9080
91- def new_logger (self , name : str ):
81+ def new_logger (name : str ):
9282 """
9383 Create a new logger with the given name.
9484 """
95- logging . basicConfig ( level = get_env_logging_level () )
85+ Logger . init_logger ( )
9686 return logging .getLogger (name )
9787
0 commit comments