'python3 - custom logger not working without basicConfig method?

I've got this code:

    def __init__(self, log_level: str = None):
        self.log_level = log_level if log_level and log_level.lower() in ['debug', 'warning', 'info',
                                                                          'error'] else 'error'
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(getattr(logging, self.log_level.upper()))

And i want to create simple logger without configurations. This code is not working without this line: logging.basicConfig()

Why? I can't really understand. So if you try something like this:

self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.debug('test')

it would not print anything. But this will:

logging.basicConfig()
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
self.logger.debug('test')

or this:

self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.DEBUG)
logging.debug("don't care")
self.logger.debug('test')


Solution 1:[1]

Logger must have defined handler. If you create logger using logging.getLogger(__name__) you must addHandler. Adding handler is part of basicConfig configuration.

import logging

logger = logging.getLogger('test')
logger.addHandler(logging.StreamHandler())  # if you comment this line, logger will not print out message
logger.setLevel(logging.DEBUG)
logger.info('hi')

You can add multiple handles to one logger. This example will print 2 messages (becasue there are two StreamHandlers).

import logging

logger = logging.getLogger('test')
logger.addHandler(logging.StreamHandler()) 
logger.addHandler(logging.StreamHandler()) 
logger.setLevel(logging.DEBUG)
logger.info('hi')

Each hadnler can have different formater, different logging_level, different output. This is usefull if you want to print in console logs from all levels, but to file only wirte critical and error level messages.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1