Why this python code filter out logs lower than INFO?

时间:2017-12-18 06:20:55

标签: python logging

import logging
# logging.basicConfig(level=logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
consoleHandler.setFormatter(logging.Formatter("%(asctime)s; %(levelname)s; %(message)s"))
logging.getLogger().addHandler(consoleHandler)

logging.debug('debug')
logging.info('test')
logging.warn('warn')
logging.error('error')
logging.fatal('fatal')

I got only the last three logs, which are equal to or higher than WARN. Could anyone please tell me why?

2 个答案:

答案 0 :(得分:3)

You set the handler's level, not the logger's. The root logger's level is still set to the root's default of WARNING, so it won't pass any messages less severe than WARNING to the handler.

答案 1 :(得分:1)

As @user2357112 has already mentioned, set level for root logger

logging.getLogger().setLevel(logging.DEBUG)

Your code would be like:

import logging
# logging.basicConfig(level=logging.DEBUG)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
consoleHandler.setFormatter(logging.Formatter("%(asctime)s; %(levelname)s; %(message)s"))
logging.getLogger().addHandler(consoleHandler)
logging.getLogger().setLevel(logging.DEBUG)

logging.debug('debug')
logging.info('test')
logging.warn('warn')
logging.error('error')
logging.fatal('fatal')#Output

#output

# 2017-12-18 12:15:49,647; DEBUG; debug
# 2017-12-18 12:15:49,648; INFO; test
# 2017-12-18 12:15:49,648; WARNING; warn
# 2017-12-18 12:15:49,648; ERROR; error
# 2017-12-18 12:15:49,648; CRITICAL; fatal