在python中,我们通常用print来打印一些信息,但是当程序停止后,在终端打印的信息也消失了,如果我们想将程序运行过程中的一些调试信息保存下来,logging是个不错的选择。logging可以将终端打印的信息全部保存在一个txt文件中,即使在程序停止后也方便我们查看。
1、定义Logger类(对logging进行封装)
实际上就是将logging类再次封装一下(当然你也可以直接使用),对于logging不再赘述,可以百度“python logging”获取更多。
实际中根据我们自身的情况来封装,这里给出一个参考:
python日志模块写入不同文件_logging模块小知识–同时往不同文件写日志
现在将新的可用代码记录如下:
class Logger():
def __init__(self, logfile='output.log'):
self.logfile = logfile
self.logger = logging.getLogger(logfile)
fh = logging.FileHandler(logfile, mode='w')
lf = logging.Formatter('[%(asctime)s] - %(message)s')
fh.setFormatter(lf)
self.logger.addHandler(fh)
logging.basicConfig(
format='[%(asctime)s] - %(message)s',
datefmt='%Y_%m_%d %H:%M:%S',
level=logging.INFO,
# filename=self.logfile
)
def info(self, msg, *args):
msg = str(msg)
if args:
print(msg % args)
self.logger.info(msg, *args)
else:
print(msg)
self.logger.info(msg)
2、如何使用?
# 实例化对象,你需要给出log文件保存地址
logger = Logger("log_file_save_file")
logger.info("程序开始运行...")
st="a dog"
logger.info("emmm %s",st)
可以看到,运行了上面的代码后,终端打印了信息,同时log文件也保存了一样的信息。
所以Logger的用法只有两步:
- 实例化
- 不断调用logger.info(str)