How To Do Logging In Python

Python provides a built-in module for logging, which helps to track events within an application. This system allows the developer to save output in a machine-readable format, or on a console that provides insight into the application’s runtime behavior.

This tutorial will guide you on how to use the logging module to add logging functionality to your Python applications.

Step 1: Import the Logging Module

To make use of logging functionality in Python, first import the module using the command import logging. This step is necessary to access the functions provided by the logging module.

Step 2: Basic Logging

For basic logging, you can use the logging.basicConfig() method that configures the root logger to a predefined format and severity level. The level parameter defines the least severity that will be dispatched to the specified destinations. Followed by, using logging.info() to write a log message of severity ‘INFO’ to the log.

Step 3: Logging Levels

Python’s logging module provides five different levels of logging that can be used to categorize and sort log messages based on their importance. They are as follows: DEBUG, INFO, WARNING, ERROR, and CRITICAL. Each level corresponds to an integer value.

  • DEBUG: Detailed information, typically of interest only when diagnosing problems (10).
  • INFO: Informational confirmation that things are working as expected (20).
  • WARNING: Something unexpected happened, or maybe to indicate some problems in the near future (30).
  • ERROR: More serious problem that prevented the program from performing a function(40).
  • CRITICAL: A serious error, indicating that the program may not be able to continue to run (50).

Step 4: Configuring the Logging Output

We can define the formatting of log output through the format parameter in basicConfig(). This might include things like time, function name, message, line number, etc.

Step 5: Writing Log Files

Instead of displaying log information onto the console, we can direct it into a file by specifying the filename parameter in basicConfig().

Full Code

Output:

INFO:root:This is an information log message
INFO:root:Admin logged in
WARNING:root:This will get logged to a file

Conclusion

Python’s logging module makes it easy to create a record of custom messages that you write. These log messages can contain crucial information when debugging your application.

Spend a few minutes to familiarize yourself with different logging levels, learn how to modify your format strings, and adapt these changes to your project to have detailed, informative logs that can prove to be lifesavers in the future.