Skip to content

Instantly share code, notes, and snippets.

@SohaibAnwaar
Created June 24, 2022 03:25
Show Gist options
  • Save SohaibAnwaar/083d8a0190b962ffb3623b1f3117b06a to your computer and use it in GitHub Desktop.
Save SohaibAnwaar/083d8a0190b962ffb3623b1f3117b06a to your computer and use it in GitHub Desktop.
Logging in python
import datetime
import logging
class Logger:
def setup_logger(self, name, log_file, level=logging.INFO):
"""To setup as many loggers as you want"""
formatter = logging.Formatter(
'%(asctime)s %(name)s - %(levelname)s - %(message)s')
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger
def get_logger(self, name: str):
"""Make a logger file if not exists, if exists then
return the old one
Args:
name (str): Name of the logger file, date will be
automatically concatinated at the start of file.
Returns:
logging.hadler : handler of the new file or existing file
"""
# Getting current date time
date = datetime.datetime.now().strftime("%Y_%m_%d")
# Concatinating date with name
logger_name_with_date = date + "_" + name
# Getting the logging file
logger = logging.getLogger(name)
# Checking if the handler exists or not
if not logger.hasHandlers():
# making file if handler not exists
logger = self.setup_logger(
name, f'"./logger/logs/{logger_name_with_date}.log')
return logger
logger = Logger()
main_log = logger("main")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment