在loggingfilter&dictConfig项目中,需要修改之前的垃圾日志输出和配置形式,研究logging模块的字典配置和过滤功能。demo如下(部分摘自python官网文档):talkischeap,showyoucode!'''引入loggingconfig模块函数,例如'''importlogging.configimportlogging#customfilterfunctionclassMyFilter(logging.Filter):'''继承logging.Filter并覆盖filter方法'''def__init__(self,param=None,param2=None):'''param:参数为定义的filter中的param字段'''self.param=paramself.param2=param2deffilter(self,record):defparam(x):returnxnotinrecord.msgifself.paramisNone:allow=Trueelse:allow=all(param(x)forxinself.param)#allow=self.paramnotinrecord.msgifallow:record.msg='changed:'+record.msg#filter可以对匹配规则做一些特殊处理#如果有是key关键字,然后在Addvalueinformationtomsg,只是为了测试,目前还没看到实际应用场景ifself.param2isnotNone:forxinself.param2.keys():ifnotparam(X):record.msg='{}'.format(self.param2[x])+record.msgreturnallow#config为字典,dictConfig解析字典数据LOGGING={'version':1.0,'formatters':{'f1':{'格式':'%(levelname)-8s%(asctime)s%(name)-8s%(filename)-15s:%(lineno)-3d%(threadName)-10s%(thread)-15d%(message)s'}},'filters':{'myfilter':{'()':MyFilter,#definedclass'param':['noshow','nodisplay'],#parameterspassedtoparamList'param2':{'key':'value'}#测试是否支持另一种形式}},'handlers':{'console':{'class':'logging.StreamHandler','formatter':'f1','filters':['myfilter'],'level':'DEBUG'},'info':{'class':'logging.handlers.TimedRotatingFileHandler','formatter':'f1','filename':'logconfig_info.log','level':'INFO','when':'M','backupCountt':180},'error':{'class':'logging.handlers.TimedRotatingFileHandler','formatter':'f1','filename':'logconfig_error.log','level':'ERROR','when':'M','backupCount':180}},'logger':{#不使用中间模式,除非代码中每个模块使用不同的日志输出格式,否则可能有用'abc':{'handlers':['console']},'a.b.c':{'handlers':['info']}},#root是所有已定义记录器的父记录器'root':{'handlers':['console','info','error'],'level':'DEBUG'#root默认是warning,所以需要设置root级别为DEBUG,通过handler中的级别控制}}logging.配置。dictConfig(LOGGING)logger3=logging.getLogger(__name__)logger1=logging.getLogger('abc')whileTrue:try:importtimelogger3.error('helloworld')logger3.warning('helloworld')logger3.info('hw')logger3.info('hwnoshow')logger3.info('hwnodisplay')logger3.debug('GET/')logger3.debug('POST/key')logger1.debug('logger1...')time.sleep(2)exceptKeyboardInterrupt:break'''日志输出:ERROR2020-04-3015:06:09,538__main__logging_config.py:104MainThread6692已更改:helloworldWARNING2020-04-3015:06:09,540__main__logging_config.py:105MainThread6692已更改:helloworldINFO2020-054:04__main__logging_config.py:106MainThread6692已更改:hwDEBUG2020-04-3015:06:09,540__main__logging_config.py:109MainThread6692已更改:GET/DEBUG2020-04-3015:06:09,540__main__logMainThread6692值已更改:POST/keyDEBUG2020-04-3015:06:09,540abclogging_config.py:112MainThread6692changed:logger1...'''总结仔细阅读官方文档很有帮助!https://docs.python.org/zh-cn...
