Python:日志输出(__new__方法构建,用名称保持logger实例的唯一性)
2018-10-21 09:53
323 查看
[code]#!/usr/bin/env python # coding:UTF-8 """ @version: python3.x @author:曹新健 @contact: 617349013@qq.com @software: PyCharm @file: 使用new方法来保证日志实例的唯一性.py @time: 2018/10/18 15:16 """ ''' 1、类实例实际上是由__new__()方法来构建的,__new__()方法的第一个参数是类本身,之后可以 定义任意参数作为构建对象之用 2、__new__()方法可以返回对象,如果返回的对象是第一个参数的实例,接下来就会执行 __iniit__()方法,__iniit__()方法第一个参数就是__new__()返回的对象。 3、如果__new__()如果没有返回第一个参数的类实例(返回别的实例或None),就不会执行 __iniit__()方法。 ''' import os,logging,sys,time class Logger(): __logger = {} def __new__(clz,name,logfile=None): if name not in clz.__logger: clz.__logger[name] = object.__new__(clz) return clz.__logger[name] def __init__(self,name,logfile=None): if name not in vars(self): self.name = name self.logger = logging.getLogger() formater = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(filename)s %(lineno)d ' '%(thread)d %(threadName)s %(process)d %(message)s') if logfile == None: cur_path = os.path.split(os.path.realpath(__file__))[0] stime = time.strftime("%Y-%m-%d",time.localtime()) logfile = cur_path + os.sep +"log_" + stime + ".log" else: logfile = logfile self.sh = logging.StreamHandler(sys.stdout) self.sh.setFormatter(formater) self.fh = logging.FileHandler(logfile) self.fh.setFormatter(formater) self.logger.addHandler(self.sh) self.logger.addHandler(self.fh) self.logger.setLevel(logging.WARNING) if __name__ == "__main__": lg = Logger("log1","222.txt") lg.logger.warning("bbb1") lg1 = Logger("log1") lg2 = Logger("log2") print(lg is lg1) print(lg is lg2)
阅读更多
相关文章推荐
- [Python] Python 之 __new__() 方法与实例化
- Python 之 __new__() 方法与实例化
- 实例解析Python中的__new__特殊方法
- Python使用logging结合decorator模式实现优化日志输出的方法
- 实例解析Python中的__new__特殊方法
- Python中的__new__()方法与实例化
- Python同时向控制台和文件输出日志logging的方法
- python中类的学习:类属性,实例属性 __new__方法:单例模式
- python之__new__方法与实例化
- Python写的Windows服务(包含日志logger输出)
- Python 之 __new__() 方法与实例化
- [Python] Python 之 __new__() 方法与实例化
- Python中的__new__()方法的使用实例
- Python 的 __new__()方法与实例化
- Python使用logging结合decorator模式实现优化日志输出的方法
- Python 之 __new__() 方法与实例化
- Python同时向控制台和文件输出日志logging的方法
- Python基于logger模块的日志输出系统
- 【python】Python 之 __new__() 方法与实例化
- 实例解析Python中的__new__特殊方法