Say Goodbye to Print(): Use Logging Module for Efficient Debugging

Date:

Share post:


Picture by Creator | DALLE-3 & Canva

 

Many people begin our programming journey with YouTube movies, and for the sake of simplicity, they typically use print() statements to trace bugs. That is honest sufficient, however as newcomers undertake this behavior, it could actually change into problematic. Though these statements would possibly work for easy scripts, as your codebase expands, this method turns into extremely inefficient. Due to this fact, on this article, I’ll introduce you to Python’s built-in logging module, which solves this downside. We’ll see what logging is, the way it differs from the print() statements, and we may also cowl a sensible instance to completely perceive its performance.

 

Why Use the Logging Module As an alternative of Print()?

 

After we speak about debugging, the Python logging module supplies way more detailed data than easy print() statements. This contains timestamps, module names, log ranges, and line numbers the place errors occurred, and so forth. These additional particulars assist us perceive the conduct of our code extra successfully. The knowledge we wish to log relies on the wants of the applying and the developer’s choice. So, earlier than we proceed additional, let’s focus on log ranges and easy methods to set them.

 

Logging Ranges

 
You’ll be able to management the quantity of knowledge you wish to see utilizing these log ranges. Every log degree has a numerical worth that denotes its severity, with larger values indicating extra extreme occasions. For instance, for those who set your log degree to WARNING, you are telling the logging module to solely present you messages which might be of WARNING degree or larger. This implies you will not see any DEBUG, INFO, or different much less extreme messages. This manner, you possibly can give attention to the vital occasions and ignore the noise

Right here’s a desk that reveals the small print of what every log degree represents:

Log Degree Numerical Worth Goal
DEBUG 10 Offers detailed data for diagnosing code-related points, comparable to printing variable values and performance name traces.
INFO 20 Used to verify that this system is working as anticipated, like displaying startup messages and progress indicators.
WARNING 30 Signifies a possible downside that will not be essential to interrupt this system’s execution however may trigger points afterward.
ERROR 40 Represents an sudden conduct of the code that impacts its performance, comparable to exceptions, syntax errors, or out-of-memory errors.
CRITICAL 50 Denotes a extreme error that may result in the termination of this system, like system crashes or deadly errors.

 

Setting Up the Logging Module

 

To make use of the logging module, you should comply with some steps for configuration. This contains making a logger, setting the logging degree, making a formatter, and defining a number of handlers. A handler principally decides the place to ship your log messages, comparable to to the console or a file. Let’s begin with a easy instance. We will arrange the logging module to do two issues: first, it will present messages on the console, giving us helpful data (on the INFO degree). Second, it will save extra detailed messages to a file (on the DEBUG degree). I might find it irresistible for those who may comply with alongside!

 

1. Setting the log degree

The default degree of the logger is ready to WARNING. In our case, our two handlers are set to DEBUG and INFO ranges. Therefore, to make sure all messages are managed correctly, we’ve got to set the logger’s degree to the bottom degree amongst all handlers, which, on this case, is DEBUG.

import logging

# Create a logger
logger = logging.getLogger(__name__)

# Set logger degree to DEBUG
logger.setLevel(logging.DEBUG)

 

 

2. Making a Formatter

You’ll be able to personalize your log messages utilizing formatters. These formatters resolve how your log messages will look. Right here, we are going to arrange the formatter to incorporate the timestamp, the log degree, and the message content material utilizing the command under:

formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

 

 

3. Creating Handlers

As mentioned beforehand, handlers handle the place your log messages shall be despatched. We’ll create two handlers: a console handler to log messages to the console and a file handler to put in writing log messages to a file named ‘app.log’.

console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(formatter)

file_handler = logging.FileHandler('app.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

 

Each handlers are then added to the logger utilizing the addHandler() technique.

logger.addHandler(console_handler)
logger.addHandler(file_handler)

 

4. Testing the Logging Setup

Now that our setup is full, let’s check if it is working appropriately earlier than shifting to the real-life instance. We will log some messages as follows:

logger.debug('It is a debug message')
logger.information('That is an information message')
logger.warning('It is a warning message')
logger.error('That is an error message')
logger.essential('It is a essential message')

 

While you run this code, it’s best to see the log messages printed to the console and written to a file named ‘app.log’, like this:

Console

2024-05-18 11:51:44,187 - INFO - That is an information message
2024-05-18 11:51:44,187 - WARNING - It is a warning message
2024-05-18 11:51:44,187 - ERROR - That is an error message
2024-05-18 11:51:44,187 - CRITICAL - It is a essential message

 
app.log

2024-05-18 11:51:44,187 - DEBUG - It is a debug message
2024-05-18 11:51:44,187 - INFO - That is an information message
2024-05-18 11:51:44,187 - WARNING - It is a warning message
2024-05-18 11:51:44,187 - ERROR - That is an error message
2024-05-18 11:51:44,187 - CRITICAL - It is a essential message

 

Logging Consumer Exercise in a Net Utility

 

On this easy instance, we are going to create a primary internet utility that logs person exercise utilizing Python’s logging module. This utility may have two endpoints: one for logging profitable login makes an attempt and the opposite to doc failed ones (INFO for fulfillment and WARNING for failures).

 

1. Setting Up Your Setting

Earlier than beginning, arrange your digital surroundings and set up Flask:

python -m venv myenv

# For Mac
supply myenv/bin/activate

#Set up flask
pip set up flask

 

2. Making a Easy Flask Utility

While you ship a POST request to the /login endpoint with a username and password parameter, the server will verify if the credentials are legitimate. If they’re, the logger information the occasion utilizing logger.information() to indicate a profitable login try. Nonetheless, if the credentials are invalid, the logger information the occasion as a failed login try utilizing logger.error().

#Making Imports
from flask import Flask, request
import logging
import os

# Initialize the Flask app
app = Flask(__name__)

# Configure logging
if not os.path.exists('logs'):
    os.makedirs('logs')
log_file="logs/app.log"
logging.basicConfig(filename=log_file, degree=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
log = logging.getLogger(__name__)


# Outline route and handler
@app.route('/login', strategies=['POST'])
def login():
    log.information('Obtained login request')
    username = request.type['username']
    password = request.type['password']
    if username == 'admin' and password == 'password':
        log.information('Login profitable')
        return 'Welcome, admin!'
    else:
        log.error('Invalid credentials')
        return 'Invalid username or password', 401

if __name__ == '__main__':
    app.run(debug=True)

 

3. Testing the Utility

To check the applying, run the Python script and entry the /login endpoint utilizing an internet browser or a software like curl. For instance:

Take a look at Case 01

 curl -X POST -d "username=admin&password=password" http://localhost:5000/login

 
Output

 
Take a look at Case 02

curl -X POST -d "username=admin&password=wrongpassword" http://localhost:5000/login

 
Output

Invalid username or password

 
app.log

2024-05-18 12:36:56,845 - INFO - Obtained login request
2024-05-18 12:36:56,846 - INFO - Login profitable
2024-05-18 12:36:56,847 - INFO - 127.0.0.1 - - [18/May/2024 12:36:56] "POST /login HTTP/1.1" 200 -
2024-05-18 12:37:00,960 - INFO - Obtained login request
2024-05-18 12:37:00,960 - ERROR - Invalid credentials
2024-05-18 12:37:00,960 - INFO - 127.0.0.1 - - [18/May/2024 12:37:00] "POST /login HTTP/1.1" 200 -

 

Wrapping Up

 

And that wraps up this text. I strongly counsel making logging part of your coding routine. It is a good way to maintain your code clear and make debugging simpler. If you wish to dive deeper, you possibly can discover the Python logging documentation for extra options and superior strategies. And for those who’re keen to boost your Python expertise additional, be at liberty to take a look at a few of my different articles:

 
 

Kanwal Mehreen Kanwal is a machine studying engineer and a technical author with a profound ardour for information science and the intersection of AI with medication. She co-authored the e book “Maximizing Productivity with ChatGPT”. As a Google Era Scholar 2022 for APAC, she champions variety and tutorial excellence. She’s additionally acknowledged as a Teradata Range in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower girls in STEM fields.

Related articles

Turning Information into Enterprise Development

In right now’s aggressive enterprise surroundings, successfully leveraging buyer information is essential for driving progress and profitability. Synthetic...

The Way forward for AI in High quality Assurance

Conventional high quality assurance (QA) processes have lengthy relied on guide testing and predefined check circumstances. Whereas efficient...

10 Finest Textual content to Speech APIs (September 2024)

Within the period of digital content material, text-to-speech (TTS) expertise has develop into an indispensable device for companies...

You.com Assessment: You May Cease Utilizing Google After Making an attempt It

I’m a giant Googler. I can simply spend hours looking for solutions to random questions or exploring new...