Last active
October 11, 2024 00:30
-
-
Save huklee/cea20761dd05da7c39120084f52fcc7c to your computer and use it in GitHub Desktop.
python Logger using example with Singleton Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import logging | |
import os | |
import datetime | |
import time | |
class SingletonType(type): | |
_instances = {} | |
def __call__(cls, *args, **kwargs): | |
if cls not in cls._instances: | |
cls._instances[cls] = super(SingletonType, cls).__call__(*args, **kwargs) | |
return cls._instances[cls] | |
# python 3 style | |
class MyLogger(object, metaclass=SingletonType): | |
# __metaclass__ = SingletonType # python 2 Style | |
_logger = None | |
def __init__(self): | |
self._logger = logging.getLogger("crumbs") | |
self._logger.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('%(asctime)s \t [%(levelname)s | %(filename)s:%(lineno)s] > %(message)s') | |
now = datetime.datetime.now() | |
dirname = "./log" | |
if not os.path.isdir(dirname): | |
os.mkdir(dirname) | |
fileHandler = logging.FileHandler(dirname + "/log_" + now.strftime("%Y-%m-%d")+".log") | |
streamHandler = logging.StreamHandler() | |
fileHandler.setFormatter(formatter) | |
streamHandler.setFormatter(formatter) | |
self._logger.addHandler(fileHandler) | |
self._logger.addHandler(streamHandler) | |
print("Generate new instance") | |
def get_logger(self): | |
return self._logger | |
# a simple usecase | |
if __name__ == "__main__": | |
logger = MyLogger.__call__().get_logger() | |
logger.info("Hello, Logger") | |
logger.debug("bug occured") |
Thank you for sharing, exactly what I need 👍
Excellent , working perfect and the formatting done well
You should probably better use a metaclass.
Why there are two assignments to the same variable? Isn't that the second one will overwrite the first?
cls._logger = super().new(cls, *args, **kwargs)
cls._logger = logging.getLogger("crumbs")
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for example! I simplified it a bit using
__new__
: