最近项目中有一个采集日志的需求,因此去了解了一下logging模块的使用,虽然网上一查就有很多资料可以参考,但还是在这里总结一下,加深理解。
一、logging模块简介
logging是python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等。
它与print相比具有以下优点:
1、可以通过设置不同的日志等级,在程序的调试和正式发布阶段分别输出调试需要输出的信息和正式运行时输出的日志。
2、我们在调试程序时往往选择print的方式输出信息,而print会将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据。
二、简单的使用
#! /usr/bin/env python
# coding: utf-8
import os
import logging
import sys
def main():
# 获取logger实例,如果参数为空则返回root logger
logger = logging.getLogger("my_log")
# 设置日志输出格式
formatter = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s')
# 文件日志
file_handler = logging.FileHandler("test.log")
file_handler.setFormatter(formatter)
# 控制台日志
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
# 为logger添加的日志处理器
logger.addHandler(file_handler)
logger.addHandler(console_handler)
# 指定日志的最低输出级别,默认为WARN级别
logger.setLevel(logging.INFO)
# 输出不同级别的log
logger.debug('this is debug info')
logger.info('this is information')
logger.warn('this is warning message')
logger.error('this is error message')
logger.critical('this is critical message')
if __name__ == '__main__':
main()
控制台输出:
F:\python\MyTest\venv\Scripts\python.exe F:/python/MyTest/common/logger.py
2019-05-19 11:15:00,733 [logger.py:75][INFO] this is information
2019-05-19 11:15:00,733 [logger.py:76][WARNING] this is warning message
2019-05-19 11:15:00,733 [logger.py:77][ERROR] this is error message
2019-05-19 11:15:00,733 [logger.py:78][CRITICAL] this is critical message
三、日志文件回滚
handler = logging.handlers.RotatingFileHandler(filename, maxBytes=10*1024*1024, backupCount=5)