如何仅记录StreamHandler日志?

时间:2019-10-17 11:45:45

标签: python logging

我只想要StreamHandler生成的日志,但是由于某种原因,一切都被记录了两次。格式化root logger似乎也不起作用。

我已经搜索了日志记录文档,并试图找出问题所在,但似乎找不到与我的问题相关的任何内容。我也尝试了几种不同的设置,但找不到任何有效的方法。

这是我尝试过的最新内容:

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)

logger.info('Modeling for date %s, saving outputs %s', date_string, save_loc_str)

输出:

2019-10-17 14:20:47,547 - __main__ - INFO - Modeling for date 2019-10-17, saving outputs to S3
INFO:__main__:Modeling for date 2019-10-17, saving outputs to S3

我也尝试过简单地在basicConfig中更改格式,但是该格式没有更新:

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

logger.info('Modeling for date %s, saving outputs %s', date_string, save_loc_str)

输出:

INFO:__main__:Modeling for date 2019-10-17, saving outputs to S3

简单

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)

logging.info('Modeling for date %s, saving outputs %s', date_string, save_loc_str)

也将不起作用,并提供与先前的输出相同的输出:/

0 个答案:

没有答案