I struggle with proper imports of logging to classes. Generally, I would like to avoid showing debug messages in the console and saving several same messages in a log file. However, when running in J. notebook via imported classes, the second class in sequence starts to show debug messages in the console during the initializing. Also, without if not logger.handlers: There is a doubling of saved messages every time. The classes import the get_logger function during the initializing. What should I do differently? Thx
import logging
from logging.handlers import TimedRotatingFileHandler
_log_format = f"%(asctime)s - [%(levelname)s] - %(name)s - " \
f"(%(filename)s).%(funcName)s(%(lineno)d) - %(message)s"
def get_timed_rotating_file_handler():
file_handler = TimedRotatingFileHandler("zon_logs.log", when='D', interval=30,
backupCount=15, delay=False, utc=False)
file_handler.setLevel(logging.DEBUG) # Log DEBUG and above to file
file_handler.setFormatter(logging.Formatter(_log_format))
return file_handler
def get_stream_handler():
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO) # Print INFO and above to console
stream_handler.setFormatter(logging.Formatter(_log_format))
return stream_handler
def get_logger(name="Admin"):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
if not logger.handlers:
logger.addHandler(get_timed_rotating_file_handler())
logger.addHandler(get_stream_handler())
return logger