How to Log to Stdout in Python

Use logging.basicConfig() to log to stdout

To log to stdout in Python:

  • Specify the format in which we want to have all logs.
  • Use the helper function .basicConfig() to perform basic logging for the logging system.
  • Use .getLogger() to create a logger with the specified name (if it is); otherwise, it will create a root logger.
  • Use .error() to log the ERROR level message on the console.

The above code block will display the following output on the console.

We used a helper function known as .basicConfig() to perform basic logging by creating the StreamHandler with the specified Formatter and adding it to a root logger.

You might have a few questions by reading the above sentence, for instance, what is StreamHandler, how they are created, what is root, and how it is being added to the root logger. Let’s address these questions before diving into more details of the .basicConfig() function.

The StreamHandler is a handler used for logging to the console. We created a root logger in our application by calling logging.getLogger(), which creates a root logger by default.

We can also name the logger of our choice by passing a custom name to this function, for example, logging.getLogger("MyLogger"). The logger.error() invokes the .basicConfig(); this is how it is added to the root logger.

Now, the point is how we are creating StreamHandler. The handlers is one of the parameters that we can set while using the .basicConfig() method. The handler parameter is iterable and used to have the handlers, for instance, logging.FilHandler() and logging.StreamHandler().

If we don’t set the handler parameter, it acts as StreamHandler by default. This is how StreamHandler is created. You can learn more about it here. Now, let’s return to the .basicConfig() method and explore more about it below.

The .basicConfig() does nothing if the root logger has configured handlers already unless force is set to True. Here, configured handlers mean that the .basicConfig() method has a handlers parameter set something as follows:

In our code example, we passed two parameters to .basicConfig() function that are briefly explained below:

  1. format – It is used to specify a particular format to display logs. If it is not given, the .basicConfig() will log in default format as logger level: logger name: log message. For instance, ERROR: root: Logging First Error.

  2. level – It denotes the logger’s level. We have six levels in the logging module: CRITICAL, ERROR, WARNING, INFO, DEBUG, and NOTSET. If no level parameter is given, it will set the logging level to NOTSET in the logging module.

Remember that the info(), debug(), error(), warning(), and critical() functions will automatically invoke .basicConfig() if any handler is not defined for a root logger.

Make sure to distinguish these logging functions from logging levels. The logging levels are not the same as logging functions but are the constants with some associated integer number.

For instance, logging.ERROR = 10. Similarly, CRITICAL, WARNING, INFO, DEBUG, and NOTSET also have some associated integers.

Next, we called the logging.getLogger() method to create a root logger. Finally, we used the logging.error() method with a logging level ERROR to log messages on a root logger.

Use logging.StreamHandler() to log to stdout

To log to stdout:

  • Use .getLogger() to create a logger named MyFirstLogger. Note that the name parameter is optional.
  • Use .StreamHandler() to log to the console.
  • Use .Formatter() to get a Formatter class’ instance initialized with the format string; this format string will be used while displaying log messages on the console or file.
  • Next, use .setFormatter() to set the formatter (created in the previous step) on StreamHandler.
  • Use .addHandler() to add the stream_handler to our logger.
  • Use .error() to log the ERROR level message on the console.

This code will print the log on the console as follows.

We used .getLogger() to create a logger with a name of our choice. We can also call this method without passing the name parameter. In that case, this function would create a root logger.

Next, we used a .StreamHandler() handler by setting a stream parameter to sys.stdout to log to the console. Here, we can change the value of the stream parameter based on where to send logging output, for instance, sys.stdout, sys.stderr, file-like object or any object supporting flush() and write().

Note that we have different handlers in the logging module that we can choose from based on project requirements, such as SocketHandler, RotatingFileHandle, DatagramHandler, NullHandler, and FileHandler.

We used StreamHandler() to log to the console, but you can also use FileHandler() to log to the file. Check the Python documentation for more details for each of the logging handlers.

Then, we used the .Formatter() function by specifying a log_format, which contained a string format to format logs. The .Formatters() are accountable for transforming internal log records into human-readable string formats.

Following the previous step, we used .setFormatter() to set the formatter on the SteamHandler, which means the logging module will use this formatter to format all the messages before displaying them on the console.

Next, we used .addHandler() to add a stream handler to the logger and finally used .error() to log the ERROR level message on the console.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *