时间:2022-03-12 08:48:58 | 栏目:Python代码 | 点击:次
代码问题:控制台和日志的文件的等级设置要放在
logger = logging.getLogger('myloger')
实例化之后才会生效 不然就被logger默认的替代了
问题:当前日志模块的等级设置 失效
现象:
console_level = "INFO" handler_level = "INFO" handler_file = logging.FileHandler(filename) handler_file.setFormatter(formatter) handler_file.setLevel(handler_level) handler_console = logging.StreamHandler() handler_console.setFormatter(formatter) handler_console.setLevel(console_level) logger = logging.getLogger('myloger') # logger.setLevel("INFO") from log import logger logger.debug("debug---------------") logger.info("info---------------") logger.warning("warning---------------") logger.error("error---------------") logger.critical("critical---------------") >>>>> 空 没有打印
解决办法 使用这个级别设置
logger.setLevel("INFO")
console_level = "INFO" handler_level = "INFO" handler_file = logging.FileHandler(filename) handler_file.setFormatter(formatter) handler_file.setLevel(handler_level) handler_console = logging.StreamHandler() handler_console.setFormatter(formatter) handler_console.setLevel(console_level) logger = logging.getLogger('myloger') logger.setLevel("INFO") # 给logger添加handler logger.addHandler(handler_file) from log import logger fee=3 data={} data['trade_amount']=100 # logger.info("ddddddddddddddddddddddddddddd") # logger.info('fee='+ str(fee) + "trade_amount"+ str(data['trade_amount'])) #logger.info('fee=' + "trade_amount"+ data['trade_amount'],) logger.info('fee ={0}+"trade_amount"'.format(data['trade_amount'])) >>>> import log start 2020-05-25 15:27:26,286 - log_level.py:17 - fee =100+"trade_amount" import log end
修改代码
日志的等级打印正常
print "import log start" import logging import datetime date = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m%d') filename = date + '.log' fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(message)s' formatter = logging.Formatter(fmt) logger = logging.getLogger('myloger') logger.setLevel(logging.DEBUG) console_level = "INFO" handler_level = "DEBUG" # logging.basicConfig(level=logging.DEBUG) handler_file = logging.FileHandler(filename) handler_file.setFormatter(formatter) handler_file.setLevel(handler_level) handler_console = logging.StreamHandler() handler_console.setFormatter(formatter) handler_console.setLevel(console_level) # 给logger添加handler logger.addHandler(handler_file) logger.addHandler(handler_console)
总结