Loading video player…

The Logging Module

The logging module in Python is a ready-to-use and powerful module that is designed to meet the needs of beginners as well as enterprise teams. It is used by most of the third-party Python libraries, so you can integrate your log messages with the ones from those libraries to produce a homogeneous log for your application.

Adding logging to your Python program is as straightforward as this:

import logging

With the logging module imported, you can use something called a “logger” to log messages that you want to see. By default, there are 5 standard levels indicating the severity of events. Each has a corresponding method that can be used to log events at that level of severity.

The defined levels, in order of increasing severity, are the following:

  • INFO

00:00 Python’s built-in logging module makes it easy to add log output to your program. It’s used by most third-party libraries, so you can combine your own log output with that of the libraries you’re using to create a comprehensive log.

00:16 And just like with any other module, accessing it is super simple, it’s just import logging.

00:24 The logging module provides a default logger that is great for getting started. We’ll talk more about loggers later, but for now, just know that a logger defines how a program should log. To log an event, we must first assign it a severity level, which represents how severe the event is.

00:43 Then, we can log only events of a specific severity level or greater, which will help us to maintain clean logs that don’t contain unnecessary events.

00:54 There are five severity levels we can use by default. They are DEBUG, INFO, WARNING, ERROR, and CRITICAL.

01:04 DEBUG is the least severe and CRITICAL is the most. As we’ll see, we can configure the logger to log only events marked as, say, WARNING or more severe, meaning that it will only log events marked as WARNING, ERROR, or CRITICAL. DEBUG and INFO events won’t be logged.

01:26 The logging module contains a function for each severity level, and they’re all used in the exact same way. If we run this program, we’ll see that the following output will be written to stdout (standard out).

01:39 As you can see, the default logger is set to a level of WARNING, meaning that only events marked as WARNING or more severe will be logged.

01:49 The default format is the level, followed by the logger name, followed by the message. root is the name of the default logger. Let’s see how we can configure this logger.

Become a Member to join the conversation.