Skip to content

Python set logging level

  • by

You can set the logging level using setLevel in Python. It sets the threshold for this logger to lvl. Logging messages which are less severe than lvl will be ignored.

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

Python set logging level example

Simple example code.

import logging

logger = logging.getLogger('dev')
logger.setLevel(logging.DEBUG)

logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

Output:

Python set logging level

Python effective logging level

The logger’s parents set the effective logging level explicitly or determined.

import logging

main_logger = logging.getLogger('main')
main_logger.setLevel(5)

dev_logger = logging.getLogger('main.dev')

print(main_logger.getEffectiveLevel())
print(dev_logger.getEffectiveLevel())

Set logging level for the module only

The normal way to do this is to define a logger for the current module – usually based on the file name – at the start of the module, and refer to this throughout.

import logging

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

def function_that_logs():
    logger.info('will log')   # note, using logger not logging
    logger.debug('will not log')

Do comment if you have any doubts or suggestions on this Python logging topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading