python logging包同时往文件和屏幕输出日志的写法

python logging包同时往文件和屏幕输出日志的写法,第1张

第一种:

import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.DEBUG)
fh = logging.FileHandler(log_file)
fh.setLevel(logging.DEBUG)
file_formatter = logging.Formatter('%(asctime)s\t%(levelname)s\t%(name)s\t%(message)s')
fh.setFormatter(file_formatter)
logger.addHandler(fh)
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)
stream_formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')
sh.setFormatter(stream_formatter)
logger.addHandler(sh)

第二种,这种写法好像会导致后面的StreamHandler 的日志会先被根过滤器的level设置过滤掉:

import logging
# 输出日志到文件,filename有参数时,日志不再输出屏幕,需要另建StreamHandler对象,输出屏幕
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO,filename=log_file)
logger = logging.getLogger() #root logger
formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s')
StreamHandler = logging.StreamHandler()
StreamHandler.setLevel(logging.WARNING)
StreamHandler.setFormatter(formatter)
logger.addHandler(StreamHandler)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/869288.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存