用户自己设置日志级别
settings.py文件中日志相关的设置:
# 日志的级别 LOG_LEVEL = 'info' # server基本路径信息 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 日志文件路径 LOG_PATH = os.path.join(BASE_DIR,'log','log.log')
我们写日志的逻辑再logger.py文件中用反射获取日志级别:
# -*- coding:utf-8 -*- import logging from server.conf.settings import LOG_PATH,LOG_LEVEL def my_log(): #生成logger对象 whw_logger = logging.getLogger('logs.log') # 确认level的值 用户写错的话就默认用DEBUG if hasattr(logging,LOG_LEVEL.upper()): level = getattr(logging,LOG_LEVEL.upper()) else: level = logging.DEBUG whw_logger.setLevel(level) # 如果handlers属性为空则添加文件操作符,不为空直接写日志 if not whw_logger.handlers: #生成handler对象 whw_fh = logging.FileHandler(LOG_PATH) whw_fh.setLevel(logging.INFO) #生成Formatter对象 file_formatter = logging.Formatter(' %(asctime)s - %(name)s - %(levelname)s - %(message)s ') #把formatter对象绑定到handler对象中 whw_fh.setFormatter(file_formatter) # 把handler对象绑定到logger对象中 whw_logger.addHandler(whw_fh) return whw_logger