使用时
from my_log import *
init_log(path,logging.DEBUG)
#注意:这样使用后,因为使用了系统默认的logging,你程序调用的其他第三方库如果也是使用logging的也会按照你格式输出到指定文件
############my_log.py###############
import logging
from logging.handlers import RotatingFileHandlerdef init_log(file_name, level):
Rthandler = RotatingFileHandler(file_name, maxBytes=10*1024*1024,backupCount=5)
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
#屏幕输出
console = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#logging.getLogger('').setLevel(logging.INFO)
logging.getLogger('').setLevel(level)
#测试代码
#logging.debug("debug message")
#logging.info("info message")
#logging.warn("warn message")
#logging.error(("error message",'asd'))
#logging.critical("critical message")
本文介绍了一个Python日志模块的配置与使用方法,包括如何设置日志级别、格式及输出方式等。通过示例代码展示了如何将日志输出到文件和控制台,并实现了日志文件的滚动保存。
17万+

被折叠的 条评论
为什么被折叠?



