Thursday, June 13, 2024
HomeMachine LearningSay Goodbye to Print(): Use Logging Module for Efficient Debugging

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

Say Goodbye to Print(): Use Logging Module
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 inexperienced persons undertake this behavior, it could actually turn into problematic. Though these statements would possibly work for easy scripts, as your codebase expands, this strategy 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 drawback. We are going to 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 a substitute of Print()?


After we speak about debugging, the Python logging module offers far more detailed data than easy print() statements. This consists of 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 data we wish to log will depend on the wants of the appliance and the developer’s desire. So, earlier than we proceed additional, let’s focus on log ranges and set them.


Logging Ranges

You may management the quantity of data 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, in case you set your log degree to WARNING, you are telling the logging module to solely present you messages which can be of WARNING degree or larger. This implies you will not see any DEBUG, INFO, or different much less extreme messages. This fashion, you may concentrate on the necessary occasions and ignore the noise

Right here’s a desk that exhibits the main points of what every log degree represents:

Log Degree Numerical Worth Function
DEBUG 10 Gives detailed data for diagnosing code-related points, resembling 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 drawback that will not be vital to interrupt this system’s execution however might trigger points in a while.
ERROR 40 Represents an surprising conduct of the code that impacts its performance, resembling 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, it’s good to comply with some steps for configuration. This consists of 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, resembling to the console or a file. Let’s begin with a easy instance. We’ll 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 in case you might 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 have now 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



2. Making a Formatter

You may personalize your log messages utilizing formatters. These formatters determine how your log messages will look. Right here, we’ll 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 can be despatched. We are going to create two handlers: a console handler to log messages to the console and a file handler to jot down log messages to a file named ‘app.log’.

console_handler = logging.StreamHandler()

file_handler = logging.FileHandler('app.log')


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



4. Testing the Logging Setup

Now that our setup is full, let’s take a look at 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')'That is an data message')
logger.warning('It is a warning message')
logger.error('That is an error message')
logger.vital('It is a vital message')


If 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:


2024-05-18 11:51:44,187 - INFO - That is an data 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 vital message


2024-05-18 11:51:44,187 - DEBUG - It is a debug message
2024-05-18 11:51:44,187 - INFO - That is an data 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 vital message


Logging Consumer Exercise in a Internet Utility


On this easy instance, we’ll create a fundamental internet utility that logs person exercise utilizing Python’s logging module. This utility could 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 Atmosphere

Earlier than beginning, arrange your digital atmosphere 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

If you ship a POST request to the /login endpoint with a username and password parameter, the server will test if the credentials are legitimate. If they’re, the logger information the occasion utilizing 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'):
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():'Obtained login request')
    username = request.type['username']
    password = request.type['password']
    if username == 'admin' and password == 'password':'Login profitable')
        return 'Welcome, admin!'
        log.error('Invalid credentials')
        return 'Invalid username or password', 401

if __name__ == '__main__':


3. Testing the Utility

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

Check Case 01

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


Check Case 02

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


Invalid username or password


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 - - - [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 - - - [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 may discover the Python logging documentation for extra options and superior methods. And in case you’re keen to boost your Python abilities 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 drugs. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions variety and tutorial excellence. She’s additionally acknowledged as a Teradata Variety in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower ladies in STEM fields.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments