How to Get Python Logger to Print to Std Out


If you use Python’s logger as follows:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # or logging.INFO

Perhaps you want to get it to print to Standard Output (stdout), then you can do the following:

Setup Logger to print to Standard Output

import logging

logger = logging.getLogger()
# logger.setLevel(logging.INFO)
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

This way you can now log straight to the console as well:

logger.info('Some text gets logged here')