Skip to content

Commit 302528f

Browse files
committed
Fix error while initializing the logs
1 parent 3e6d8fc commit 302528f

File tree

1 file changed

+23
-33
lines changed

1 file changed

+23
-33
lines changed

api/src/shared/common/logging_utils.py

Lines changed: 23 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import logging
22
import os
3+
import threading
4+
35
from google.cloud.logging.handlers import CloudLoggingHandler
46
import google.cloud.logging
57
from google.cloud.logging_v2 import Client
@@ -14,7 +16,7 @@ def get_env_logging_level():
1416
def is_local_env():
1517
return os.getenv("K_SERVICE") is None
1618

17-
19+
lock = threading.Lock()
1820
class 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

Comments
 (0)