Search code examples
pythonpython-2.7loggingpython-logging

Python Logging: INFO,DEBUG Logs not displayed


Python Version : 2.7

I am using the below code to display the logs on console. However, INFO and DEBUG logs are not displayed.

Code

import logging
class LogTest():
    def __init__(self):
        logger_obj = logging.getLogger('Sample Logger')
        console_logger = logging.StreamHandler()
        console_logger.setLevel(logging.INFO)

        logger_obj.addHandler(console_logger)
        logger_obj.info('INFO LOG')
        logger_obj.debug('DEBUG LOG')
        logger_obj.error('ERROR LOG')
        logger_obj.warning('WARNING LOG')
        logger_obj.critical('CRITICAL LOG')

if __name__ == '__main__':
    log_instance = LogTest()

Output

ERROR LOG
WARNING LOG
CRITICAL LOG

According to python documentation, logs above the set logging level should be displayed. Can anyone explain why this is happening?

Also, How should I enable DEBUG and INFO logs?


Solution

    1. You're setting log level for stream handler while you have to do it for logger itself (logger_obj in your case). Handler is used to apply additional filters to logs, but they are first filtered by logger itself.

    2. DEBUG > INFO, so you have to set level to DEBUG, not INFO (If you want to see all logs).

    in short, use:

    logger_obj.setLevel(logging.DEBUG)