logging模块
logging模块
logging模块两种应用
1、函数级
关注 输出和设置
import logging logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s %(threadName)s %(thread)d %(process)d',datefmt='%a, %d %b %Y %H:%M:%S') logging.info("error") logging.debug('debug message')
这里还可以显示出来 线程和进程%(thread)d %(process)d
2、对象级
1)程序设置
关注对象,方法和场景
logger -> getLogger
句柄对象 -> 1)FileHandler 2)StreamHandler
设置对象 -> Formatter
过滤器 -> Filter
场景为,先定义日志对象,然后定义句柄对象确认输出目标,然后设置输出的格式,中间有添加到句柄对象的过程。
import logging logger1 = logging.getLogger("fir") logger1.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s \ - %(levelname)s - %(message)s') # 1config cm = logging.StreamHandler() # 2out cm.setFormatter(formatter) # 3setting #fm = logging.FileHanfler("D:\FIR.log") filter1 = logging.Filter("fir") #logger1.addFilter(filter1) cm.addFilter(filter1) logger1.addHandler(cm) # 4log #logger1.setFormatter(formatter) >AttributeError:\ #'Logger' object has no attribute 'setFormatter' logger1.debug('debug log1') logger1.info('info log1') logger1.error('error log1')
2)文本配置