Logger.py 1.9 KB
from django.conf import settings
import logging

# If django project is in /src/ :
#RELATIVE_PATH_TO_LOG_DIR = '../logs/'
#logging.basicConfig(filename='%s/../logs/pyros.log'%(settings.BASE_DIR), format='-> At : [%(asctime)s]\n\t By module [%(module)s] logger : [%(name)s] : "%(message)s"', level=logging.DEBUG)
# If django project is in /src/core/pyros_django/ : 
RELATIVE_PATH_TO_LOG_DIR = '../../../logs'
logging.basicConfig(filename = f'{settings.BASE_DIR}/{RELATIVE_PATH_TO_LOG_DIR}/pyros.log', 
                    format = '-> At : [%(asctime)s]\n\t By module [%(module)s] logger : [%(name)s] : "%(message)s"', 
                    level = logging.DEBUG)
#logging.basicConfig(filename='%s/../../../logs/pyros.log'%(settings.BASE_DIR), format='-> At : [%(asctime)s]\n\t By module [%(module)s] logger : [%(name)s] : "%(message)s"', level=logging.DEBUG)

def setupLogger(logger_name, log_file, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('[%(message)s] at %(filename)s : %(lineno)s')
    #fileHandler = logging.FileHandler('%s/../logs/%s.log'%(settings.BASE_DIR, log_file), mode='w')
    fileHandler = logging.FileHandler(f'{settings.BASE_DIR}/{RELATIVE_PATH_TO_LOG_DIR}/{log_file}.log', mode='w')
    fileHandler.setFormatter(formatter)
    # streamHandler = logging.StreamHandler()
    # streamHandler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(fileHandler)
    # l.addHandler(streamHandler)
    return (logging.getLogger(logger_name))


class Logger:
    def __init__(self, name: str, file: str):
        super().__init__()
        self.logger = setupLogger(name, file)

    def log(self, message):
        if settings.DEBUG:
            self.logger.info(message)

    def info(self, message: str):
        if settings.DEBUG:
            self.logger.info(message)

    def debug(self, message: str):
        if settings.DEBUG:
            self.logger.debug(message)