Search code examples
logginggoogle-colaboratorylogfile

Logging does not output debug & info log


I have written the following code:

    import logging

    logging.basicConfig(filename='rb-log.log', 
                    format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                    level=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')

The log file contains:

   646-2021-10-30 22:08:39,404-WARNING-This is a warning message
   646-2021-10-30 22:08:39,406-ERROR-This is an error message
   646-2021-10-30 22:08:39,407-CRITICAL-This is a critical message

Only WARNING, ERROR & CRITICAL log is being written into the log file. DEBUG & INFO logs are not written. What am I doing wrong here?


Solution

  • You don't show how you've set up logger, so it appears it's before the configuration. The configuration (logging.basicConfig(...)) won't apply to a logger that's already set up; your logger is using the default level of WARN.

    You could use the convenience methods on logging as shown in https://docs.python.org/3/howto/logging.html#logging-to-a-file

    logging.basicConfig(filename='rb-log.log', 
                        format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                        level=logging.DEBUG)
    logging.debug('This is a debug message')
    logging.info('This is an info message')
    

    or configure logging before creating your logger:

    logging.basicConfig(filename='rb-log.log', 
                        format='%(process)d-%(asctime)s-%(levelname)s-%(message)s',
                        level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    logger.debug('This is a debug message')
    logger.info('This is an info message')