python--配置日志
做项目时,经常会碰到各种各样的错误,如果没有一个层次分明的日志文件,就好像无头苍蝇,不知道该咋办,既耗时又耗力,
今天给大家带来一个配置层次分明的日志方法
1.先导入所需的模块
import logging
from common import read_conf(日志等级存放在配置中,所以导入了read_conf)
import time(为生成每天的日志)
import os
2.设置日志目录、等级及内容
logger = logging.getLogger()
目录:
path=os.path.join(os.path.dirname(os.path.dirname(__file__)),"封装","log",time.strftime("%Y-%m-%d"))
if not os.path.isdir(path):
os.mkdir(path)
日志名称:
log_path = os.path.join(path,"log.text")
日志内容:
msg=logging.Formatter("%(levelname)s %(filename)s %(asctime)s %(lineno)s %(message)s")
b=logging.StreamHandler()
a = logging.FileHandler(log_path, "a+", encoding="utf8")
a.setFormatter(msg)
b.setFormatter(msg)
if logger.__dict__["handlers"] == []:
logger.addHandler(b)
logger.addHandler(a)
日志级别:
def level1():
logger.setLevel(read_conf.level1)
return logger
def level2():
logger.setLevel(read_conf.level2)
return logger
def level3():
logger.setLevel(read_conf.level3)
return logger
def level4():
logger.setLevel(read_conf.level4)
return logger
def level5():
logger.setLevel(read_conf.level5)
return logger
PS:level1--level5分别对应debug--critical