dimanche 14 août 2022

How to use Logger class as Singleton

I want to use my Logger class as a Singleton. But I can't understand what exactly I am doing wrong even after the reading several topics and wathcing a lot of videos I am still confused what I am doing wrong. Below is my class

import inspect
import logging as log
from env_setup import *


class Logger:
    @staticmethod
    def custom_logger(level):
        logger_name = inspect.stack()[1][3]
        logger = log.getLogger(logger_name)
        logger.setLevel(level)
        log_book = log.FileHandler(LOG_FILE) # LOG_FILE is getting from env_setup module where the path to file stored in
        formatter = log.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt='%m/%d/%Y %I: %M: %S %p')
        log_book.setFormatter(formatter)
        logger.addHandler(log_book)
        return logger

And the usage is as below in another module:

class SomeClass:
    def __init__(self):
        self.log = Logger.custom_logger(level=log.INFO)

    def some_func(self):
        try:
            1 == 1
            self.log.info('passed as correct')
        except Exception:
            self.log.error('errored')
            raise Exception('Exception raised')

What exactly should I change in order to make this class as a Singleton. I need to store this object as a single object in my code. Thanks.

Aucun commentaire:

Enregistrer un commentaire