Python练手,封装日志模块,v1
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python练手,封装日志模块,v1相关的知识,希望对你有一定的参考价值。
代码:Python3
# -*- coding: utf-8 -*- ''' --封装了logging模块,仅保留关键设置,美化了输出格式 ''' import sys,random,time import logging as lg def getRandomInt(digits): ''' @args: int digits @returns: string ''' return random.randint(1,10**digits-1).__str__().zfill(digits) def getNowDate(fmt): ''' @args: string fmt @returns: string ''' return time.strftime(fmt,time.localtime()).__str__() def getOriginPath(): ''' @returns: string ''' return sys.argv[0] class XLogger(): ''' -日志记录器 -封装了logging模块,舍弃了繁琐了设置,仅保留关键设置,美化了输出格式 -大概用法:-创建XLogger,添加XHandler -对于XLogger -允许设置日志级别、记录器名称、父子记录器的传播功能 -对于XStreamHandler 控制台输出 -不允许设置 -对于XFileHandler 文件输出 -允许设置文件路径,文件写入方式:覆盖/追加 ''' levelMap = {'DEBUG':lg.DEBUG, 'INFO':lg.INFO, 'WARN':lg.WARNING, 'ERROR':lg.ERROR, 'CRITICAL':lg.CRITICAL} def __init__(self): self.logger = None self.handlers = [] self.name = 'root' self.level = 'INFO' self.propagate = False def setName(self,name): ''' @args: string name 关于记录器-记录器名称(默认:root)(名称可体现记录器的父子关系) @returns: self ''' self.name = name return self def setLevel(self,level): ''' @args: string level 关于记录器-日志级别 DEBUG/INFO/WARN/ERROR/CRITICAL(默认:INFO) @returns: self ''' self.level = level return self def setPropagate(self,propagate): ''' @args: boolean propagate 关于记录器-是否开启父子日志记录器的向上传播功能(默认:False) - 若开启,子记录器会获得父记录器的全部Handler, - 需注意重复添加Handler以免产生重复日志 @returns: self ''' self.propagate = propagate return self def addHandler(self,xHandler): self.handlers.append(xHandler) return self def instantiate(self): ''' @returns: self ''' #Logger self.logger = lg.getLogger(self.name) self.logger.setLevel(XLogger.levelMap.get(self.level)) self.logger.propagate = self.propagate #Handler for handler in self.handlers : self.logger.addHandler(handler.handler) return self def debug(self,layer,message): self.logger.debug('DBUG ' + '|··' * layer +message) def info(self,layer,message): self.logger.info('INFO ' + '|··' * layer + message) def warning(self,layer,message): self.logger.warning('WARN ' + '|··' * layer + message) def error(self,layer,message): self.logger.error('ERRO ' + '|··' * layer + message) def critical(self,layer,message): self.logger.critical('CRIT ' + '|··' * layer + message) class XHandler: def __init__(self): self.handler = None self.formatter = lg.Formatter('[%(name)s] %(asctime)s %(message)s','%y/%m/%d %H:%M:%S') class XFileHandler(XHandler): def __init__(self): XLogger.XHandler.__init__(self) self.file = getOriginPath()+'.'+getNowDate("%Y%m%d%H%M%S")+getRandomInt(4)+'XLOG' self.model = 'w' def setFile(self,file): ''' @args: string file 关于文件打印-文件路径(默认:起源执行文件.时间+随机数+XLOG) @returns: self ''' self.file = file return self def setModel(self,model): ''' @args: string model 关于文件打印-文件写入模式 w覆盖 a追加(默认:w) @returns: self ''' self.model = model return self def instantiate(self): ''' @returns: self ''' self.handler = lg.FileHandler(self.file,mode=self.model.lower(),encoding='UTF-8',delay=False) self.handler.setFormatter(self.formatter) print('xlog file:',self.file) return self class XStreamHandler(XHandler): def __init__(self): XLogger.XHandler.__init__(self) def instantiate(self): ''' @returns: self ''' self.handler = lg.StreamHandler() self.handler.setFormatter(self.formatter) return self
测试:
dir_='D:\\Users\\ex-hexuwen001\\Desktop\\Work\M1-APPS\\using__apps_data\\eclipse_workspace\\myPython\\src' file1=dir_+'\\1.xlog' file2=dir_+'\\2.xlog' logger1 = XLogger().setLevel('DEBUG').setPropagate(True).setName('aaaa') .addHandler(XLogger.XFileHandler().setFile(file1).setModel('a').instantiate()) .addHandler(XLogger.XStreamHandler().instantiate()) .instantiate() logger1.debug(0,"牛逼局域网") logger1.info(1,'广东省') logger1.warning(2,'肇庆市') logger1.error(2,'高要市') logger1.critical(3,'牛逼镇') logger2 = XLogger().setLevel('DEBUG').setPropagate(True).setName('aaaa.bbbb') .addHandler(XLogger.XFileHandler().setFile(file2).setModel('a').instantiate()) .addHandler(XLogger.XStreamHandler().instantiate()) .instantiate() logger2.debug(0,"牛逼局域网") logger2.info(1,'广东省') logger2.warning(2,'肇庆市') logger2.error(2,'高要市') logger2.critical(3,'牛逼镇')
输出:
xlog file: D:\Users\ex-hexuwen001\Desktop\Work\M1-APPS\using__apps_data\eclipse_workspace\myPython\src\1.xlog [aaaa] 18/01/12 14:14:23 DBUG 牛逼局域网 [aaaa] 18/01/12 14:14:23 INFO |··广东省 [aaaa] 18/01/12 14:14:23 WARN |··|··肇庆市 [aaaa] 18/01/12 14:14:23 ERRO |··|··高要市 [aaaa] 18/01/12 14:14:23 CRIT |··|··|··牛逼镇 xlog file: D:\Users\ex-hexuwen001\Desktop\Work\M1-APPS\using__apps_data\eclipse_workspace\myPython\src\2.xlog [aaaa.bbbb] 18/01/12 14:14:23 DBUG 牛逼局域网 [aaaa.bbbb] 18/01/12 14:14:23 DBUG 牛逼局域网 [aaaa.bbbb] 18/01/12 14:14:23 INFO |··广东省 [aaaa.bbbb] 18/01/12 14:14:23 INFO |··广东省 [aaaa.bbbb] 18/01/12 14:14:23 WARN |··|··肇庆市 [aaaa.bbbb] 18/01/12 14:14:23 WARN |··|··肇庆市 [aaaa.bbbb] 18/01/12 14:14:23 ERRO |··|··高要市 [aaaa.bbbb] 18/01/12 14:14:23 ERRO |··|··高要市 [aaaa.bbbb] 18/01/12 14:14:23 CRIT |··|··|··牛逼镇 [aaaa.bbbb] 18/01/12 14:14:23 CRIT |··|··|··牛逼镇
以上是关于Python练手,封装日志模块,v1的主要内容,如果未能解决你的问题,请参考以下文章