01单例模式案例赏析

import fcntl #文件锁模块


"""
单例阻塞式日志案例

将模型应用在日志模块中(这个日志模块是阻塞的)
不同的事件记录到日志要按照不同的级别
"""
import time
import os
class Log_SigletonObject:
    __instance=None
    class __File_Object:
        def __init__(self):
            self.file_path=None
        def __str__(self):
            return self.file_path

        #各级别日志消息记录
        def error(self,msg,level='ERROR'):
            self.__write_log(msg,level)
        def warn(self,msg,level='WARN'):
            self.__write_log(msg,level)
        def info(self,msg,level='INFO'):
            self.__write_log(msg,level)
        def debug(self,msg,level='DEBUG'):
            self.__write_log(msg,level)
        def __write_log(self,msg,level):
            with open(self.file_path,'a+') as file:
                fcntl.flock(file.fileno(),fcntl.LOCK_EX) #这是个阻塞锁,防止文件被写乱
                file.write('[{}:{}] {}\n'.format(level,time.time(),msg))

    def __new__(cls,*args,**kwargs):

        if not cls.__instance:
            cls.__instance=cls.__File_Object()
        return cls.__instance

import threading
import random

#处理器
def handler(flag):
    log_sig=Log_SigletonObject()
    log_sig.file_path='./log01.txt'
    log_level=[log_sig.error,log_sig.warn,log_sig.info,log_sig.debug]
    msg_info=['error','warn','info','debug']
    for _ in range(3):
        time.sleep(random.randint(0,3)) #模拟耗时操作
        current_index=random.randint(0,3)
        log_level[current_index]("id(log_sig):{} {}_handler:{}"
                                 .format(id(log_sig),flag,msg_info[current_index]))


def main_04():
    t1=threading.Thread(target=handler,args=('线程1',))
    t2=threading.Thread(target=handler,args=('线程2',))
    t3=threading.Thread(target=handler,args=('线程3',))
    t4=threading.Thread(target=handler,args=('线程4',))

    t1.start()
    t2.start()
    t3.start()
    t4.start()

'''
执行:
   main_04() 
执行结果:
    tail -f log01.txt (通过这命令来监控log01.txt)
    
    [INFO:1548684915.505127] id(log_sig):139650923574160 线程2_handler:info
    [WARN:1548684915.505258] id(log_sig):139650923574160 线程2_handler:warn
    [DEBUG:1548684916.5052104] id(log_sig):139650923574160 线程1_handler:debug
    [INFO:1548684917.505918] id(log_sig):139650923574160 线程2_handler:info
    [WARN:1548684917.506108] id(log_sig):139650923574160 线程3_handler:warn
    [ERROR:1548684917.5062473] id(log_sig):139650923574160 线程4_handler:error
    [ERROR:1548684918.507406] id(log_sig):139650923574160 线程4_handler:error
    [ERROR:1548684919.5073886] id(log_sig):139650923574160 线程3_handler:error
    [WARN:1548684919.507493] id(log_sig):139650923574160 线程3_handler:warn
    [DEBUG:1548684919.5079567] id(log_sig):139650923574160 线程1_handler:debug
    [DEBUG:1548684919.5080187] id(log_sig):139650923574160 线程1_handler:debug
    [DEBUG:1548684919.508491] id(log_sig):139650923574160 线程4_handler:debug

'''

你可能感兴趣的:(01单例模式案例赏析)