The singleton pattern of Python design pattern - realize the singleton of the logger

1. Introduction to Singleton Mode

Overview: Requires one and only one instance of a class, and provides a global access point.

Application scenarios: resource pools such as log insertion, timers, permission verification, recycle bins, website counters, thread pools, database connection pools, etc.

 

 Second, the realization of the log recorder

The instantiation process of an object is to execute the class __new__方法first.If we don't write it, the object __new__method will be called by default , returning an instantiated object, and then calling __init__方法to initialize this object.We can implement a singleton based on this.

__new__方法中First judge whether there is an instance in a class , if there is an instance, it will return directly, if there is no instance, it will be created.

# coding=utf-8

class Singleton(object):
    """
    单例类
    """
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(Singleton, cls).__new__(cls)     # python3
            # cls._instance = super(Singleton, cls).__new__(cls,*args, **kwargs)     # python2
        return cls._instance

class Logger(Singleton):
    """
    日志
    """
    def __init__(self, file_name):
        self.filename = file_name

    def _write_log(self, level, msg):
        with open(self.filename, "a") as log_file:
            log_file.write("[{0}]{1}\n".format(level, msg))

    def critical(self, msg):
        self._write_log("CRITICAL", msg)

    def error(self, msg):
        self._write_log("ERROR", msg)

    def warn(self, msg):
        self._write_log("WARN", msg)

    def info(self, msg):
        self._write_log("INFO", msg)

    def debug(self, msg):
        self._write_log("DEBUG", msg)

if __name__ == '__main__':
    log1 = Logger("logger1.log")
    log2 = Logger("logger2.log")
    print(id(log1), log1.filename)
    print(id(log2), log2.filename)
    log1.info("log1************")
    log1.warn("log1************")
    log2.info("log2************")
    log2.warn("log2************")

The console output is as follows:

566521222648 logger2.log
566521222648 logger2.log

Generate a logger2.log file, the content of the file is as follows:

[INFO] log1 ************
[WARN]log1************
[INFO] log2 ************
[WARN]log2************

The results show that: the content of the log information is recorded in the same file

 

Reference

[Wessel Badenhorst]Practical Python Design Patterns:Pyrhonic Solution to Common Problems

https://blog.csdn.net/sxb0841901116/article/details/78506643

https://blog.csdn.net/Burgess_zheng/article/details/86762248#%C2%A0%20%C2%A0%C2%A0%20%C2%A0%20%C2%A05.%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%EF%BC%88Singleton%EF%BC%89

https://www.runoob.com/design-pattern/singleton-pattern.html

Guess you like

Origin blog.csdn.net/qq_40602000/article/details/106573829