简体   繁体   中英

Should `logging.basicConfig(level=logging.INFO)` accept only INFO level of logging?

Here is the sample code from source: https://docs.python.org/3/howto/logging.html

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')

I thought the level=logging.DEBUG of below code

logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)

making the logging accept only logging.DEBUG only. Then why info , warning , error work

The logging levels of python is arranged in the following order:

  1. CRITICAL
  2. ERROR
  3. WARNING
  4. INFO
  5. DEBUG
  6. NOTSET

If you set the root logger level when configuring as logging.DEBUG , it will write all the logs with the levels above that.

Example:

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')

Output:

DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö

If you set the root logger level when configuring as logging.ERROR , it will write only the CRITICAL logs and ERROR logs.

Example:

import logging
logging.basicConfig(filename='example.log', level=logging.ERROR)
logging.warning('this is warning')
logging.info('this is info')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
logging.critical('And non-ASCII stuff, too, like Øresund and Malmö 2')

Output:

ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö
CRITICAL:root:And non-ASCII stuff, too, like Øresund and Malmö 2

Log levels are actually integers and they set a threshold. For instance logging.DEBUG is 10 and logging.INFO is 20. When you set a log level, you allow that level and anything larger . When you set DEBUG any level 10 or greater will log. Filter objects are commonly used if you want a different level of control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM