How To Write A Log In Python

Ever wondered how to create and manage logs in Python? Logging is an essential part of any programming project, especially for debugging and troubleshooting purposes.

Python provides an in-built module for logging, allowing you to both store your log in a file and display it to the console. This guide will walk you through a series of steps to implement logging in Python.

Step 1: Import The Logging Module

The first step is to import Python’s in-built logging module. You can do this with the following code:

Step 2: Configure The Logging Module

The next step is to configure how the logging module behaves using the basicConfig() function.

In the example above, we’re configuring the logger to write messages to a file called app.log (filename=’app.log’). Messages will overwrite the file each time the program is run (filemode=’w’). The format of the log message is defined (format=’%(name)s – %(levelname)s – %(message)s’).

Step 3: Write A Log

Now, you can write a log. Python allows for various levels of logging:

DEBUGDetailed information, typically of interest only when diagnosing problems.
INFOConfirmation that things are working as expected.
WARNINGAn indication that something unexpected happened, or there might be some problem in the near future (e.g., ‘disk space low’).
ERRORThe more serious problem that prevented the software from performing a function.
CRITICALA very serious error, indicating that the program itself may be unable to continue running.

You can write a log at any of these levels as follows:

This will print the log messages to your console and also write them to your log file.

Step 4: Check The Output

Finally, you can open your log file to see the outputs. The file will look like this:

root - WARNING - This is a warning message
root - ERROR - This is an error message
root - CRITICAL - This is a critical message

You will notice that the DEBUG and INFO messages did not get logged. This is because, by default, the logging module logs the messages with a severity level of WARNING or above. You can change this by setting the level in the basicConfig() function like so:

In the aforementioned way, you can have complete control over what you want to print out to the log file.

The full code:

Following these easy steps, you can easily set up and manage logs in your Python applications. We hope you found this tutorial helpful!

Conclusion

Logging is an essential part of programming that aids in identifying bugs and troubleshooting issues. Python’s built-in logging module makes it easy to implement versatile and adaptable logging in your applications. Mastering the usage of this module can help you create more efficient, maintainable, and bug-free code.