Learning logging module: INFO message not displayed

Hi,
I am learning how to use the logging module.

Here the desired design:
Inside main.py file a customized logger is created, for instance:

import logging
import logging.handlers
from mypath.myprogram import program_run

def logging_setup():
    class CustomFormatter(logging.Formatter):
        grey = "\x1b[38;21m"
        yellow = "\x1b[33;21m"
        red = "\x1b[31;21m"
        blue = "\x1b[34;21m"
        bold_red = "\x1b[31;1m"
        reset = "\x1b[0m"
        format_info = "[%(levelname)s - %(asctime)s]: "
        format_message = "%(message)s"

        FORMATS = {
            logging.DEBUG: grey + format_info + reset + format_message,
            logging.INFO: blue + format_info + reset + format_message,
            logging.WARNING: yellow + format_info + reset + format_message,
            logging.ERROR: red + format_info + reset + format_message,
            logging.CRITICAL: bold_red + format_info + reset + format_message
        }

        def format(self, record):
            log_fmt = self.FORMATS.get(record.levelno)
            formatter = logging.Formatter(log_fmt, datefmt='%Y-%m-%d %H:%M:%S')
            return formatter.format(record)

    # Create custom formatter
    custom_formatter = CustomFormatter()

    # Configure the root logger named app
    custom_logger = logging.getLogger('app')

    # set up the console handler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(custom_formatter)

    # add handlers
    custom_logger.addHandler(console_handler)

if __name__ == '__main__':
    # set up logging
    logging_setup()
    # get logger
    logger = logging.getLogger('app')
    # test logger
    logger.info('information message') # this is not printed
    logger.error('error message') # this is printed
    # test the logger inside another file
    program_run()

Then inside the other file mypath/myprogram.py:

import logging
def program_run():
    logger = logging.getLogger('app')
    logger.info('information in another file') # this is not printed
    logger.error('error in another file') # this is printed

The problem is that the INFO level messages are not displayed, am I missing something?

I get, in Python 3.10.12,

> python main.py
[ERROR - 2023-08-30 10:24:53]: error message
[ERROR - 2023-08-30 10:24:53]: error in another file

The default logger log level is WARNING. Try adding logger.setLevel(logging.INFO).
If you want that as general default, then you could also add it to your initialization function.

2 Likes

Thank you, I did not notice that I could set the level for both loggers and handlers :face_in_clouds:

FYI the 0 is not required. You can use “\x1b[m”.

The 0m has been cargo culted for years.

1 Like