How to Log to Stdout with Python?

Better Stack Team
Updated on May 4, 2022

Using Basic Configuration

Python, by default, logs to a console. You can call the function on the module:

 
import logging

logging.warning("Warning.")

OUTPUT
WARNING:root:Warning.

Python already provides default formatting.

Using Provided Classes

You can also use the provided classes:

 
import logging

logger = logging.getLogger("nameOfTheLogger")
ConsoleOutputHandler = logging.StreamHandler()

logger.addHandler(ConsoleOutputHandler)

logger.warning("Warning.")

Create a new logger and a new handler. Assign the class StreamHandler to the handler and assign the handler to the logger. The output will be the following: