How to get Python logger to Print to std out

0 min read 81 words

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')
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags