Skip to content
  • SiteMap
  • Our Services
  • Frequently Asked Questions (FAQ)
  • Support
  • About Us

UpdateGadh

Update Your Skills.

  • Home
  • Projects
    •  Blockchain projects
    • Python Project
    • Data Science
    •  Ai projects
    • Machine Learning
    • PHP Project
    • React Projects
    • Java Project
    • SpringBoot
    • JSP Projects
    • Java Script Projects
    • Code Snippet
    • Free Projects
  • Tutorials
    • Ai
    • Machine Learning
    • Advance Python
    • Advance SQL
    • DBMS Tutorial
    • Data Analyst
    • Deep Learning Tutorial
    • Data Science
    • Nodejs Tutorial
  • Blog
  • Contact us
  • Toggle search form
Logging in Python

Logging in Python: A Comprehensive Guide

Posted on February 11, 2025February 11, 2025 By Rishabh saini No Comments on Logging in Python: A Comprehensive Guide

Logging in Python

Introduction

Logging is an essential aspect of software development that allows developers to track and record events that occur during program execution. Python’s built-in logging module provides a robust framework for logging messages at different severity levels, helping developers diagnose issues efficiently.

In this tutorial, we will explore the fundamentals of the logging module, including its features, logging levels, basic configurations, formatting, and advanced usage.

Complete Python Course with Advance topics:-Click here

What is Logging?

Logging in Python is a mechanism for tracking events that happen when a program runs. It helps developers understand what the program is doing and aids in debugging. Instead of using print statements for debugging, logging provides a structured and configurable way to record messages.

Why Use Logging?

  • Diagnosing Problems: Helps trace the cause of errors or unexpected behaviors.
  • Record-Keeping: Maintains logs for auditing and monitoring purposes.
  • Debugging: Provides more context than simple print statements.
  • Error Handling: Helps in identifying and handling runtime issues.

How Logging Works

The logging module provides five levels of logging severity:

LevelNumeric ValueDescription
DEBUG10Detailed debugging information.
INFO20General events, confirming that things are working as expected.
WARNING30An indication of something unexpected that might cause issues later.
ERROR40A serious problem that prevents the program from executing a specific task.
CRITICAL50A severe error that might cause the program to stop running entirely.

Example:

import logging

logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
logging.critical("This is a critical message")

Output:

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

Explanation:

  • By default, Python logs messages at WARNING level and above.
  • DEBUG and INFO messages are ignored unless explicitly configured.

Configuring Logging

To change the default behavior, we can use basicConfig() to specify the logging level, format, and output destination.

Setting the Logging Level

import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug("This debug message will be displayed now")

Output:

DEBUG:root:This debug message will be displayed now

Logging to a File

Instead of printing logs to the console, we can save them to a file.

import logging

logging.basicConfig(filename='app.log', filemode='w', level=logging.WARNING)
logging.warning("This warning will be logged in the file")

This creates a file app.log with the logged message.

Custom Formatting

We can format log messages to include additional details like timestamp, function name, and log level.

import logging

logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logging.info("User logged in")

Output:

2025-02-11 10:30:45,123 - INFO - User logged in

Setting Date and Time Format

import logging

logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')
logging.warning("Database connection failed")

Output:

11-Feb-25 10:45:30 - Database connection failed

Using Logger Objects

Instead of using the root logger, we can create custom loggers for better control.

import logging

# Create logger
logger = logging.getLogger("CustomLogger")
logger.setLevel(logging.DEBUG)

# Create handler
handler = logging.FileHandler("custom.log")
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Logging messages
logger.debug("Debugging the application")
logger.info("Application started")

This setup allows better organization and log management, especially for large applications.

Capturing Stack Traces

We can log stack traces for exceptions using exception(), which automatically includes traceback information.

import logging

logging.basicConfig(level=logging.ERROR)

try:
    result = 10 / 0
except ZeroDivisionError:
    logging.exception("An error occurred")

Output:

ERROR:root:An error occurred
Traceback (most recent call last):
  File "example.py", line 5, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

Logging Variable Data

We can pass dynamic data into log messages using string formatting.

import logging

user = "Alice"
logging.error("%s attempted an unauthorized action", user)

Or using f-strings (Python 3.6+):

logging.error(f"{user} attempted an unauthorized action")

Download New Real Time Projects :-Click here
Complete Advance AI topics:- CLICK HERE

Conclusion

Logging in Python is a powerful tool that helps developers track and troubleshoot issues effectively. By understanding different log levels, configurations, and advanced features like loggers, handlers, and formatting, developers can enhance their debugging experience and maintain cleaner code.

If you want to dive deeper, refer to Python’s official documentation: Python Logging Module.


Logging in Python
Logging in Python example
Logging in Python to file
python logging to console
logger.info python
Logging in Python to stdout
python logging best practices
Logging in Python levels
python logging not printing
online python compiler
logging in python w3schools

 

Post Views: 550
Python Interview Question Tags:how to log messages in python, logging, logging in python, logging module, logging module in python, logging python, logging tutorial python, Python, python for beginners, python logger, python logging, python logging advanced tutorial, python logging beginner, python logging best practices, python logging example, python logging for beginners, python logging module, python logging tutorial, python logs, python programming, Python Tutorial

Post navigation

Previous Post: Cinema Seat Reservation System in PHP with Source Code
Next Post: SQL ORDER BY LIMIT – Retrieve Specific Rows from a Database

More Related Articles

Create a Virtual Environment in Python How to Create a Virtual Environment in Python Python Interview Question
How to Read a CSV File in Python? - How to Read a CSV File in Python How to Read a CSV File in Python? Python Interview Question
How to Read a Text File in Python How to Read a Text File in Python Python Interview Question

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

  1. How to Install Python on Windows: A Step-by-Step Guide
  2. How to Run Python Program: A Comprehensive Guide for Python Programmers
  3. How to Append Elements to a List in Python
  4. How to Clear the Python Shell
  5. How to Print Patterns in Python
  6. Insertion Sort in Python

Most Viewed Posts

  1. Top Large Language Models in 2025
  2. Online Shopping System using PHP, MySQL with Free Source Code
  3. login form in php and mysql , Step-by-Step with Free Source Code
  4. Flipkart Clone using PHP And MYSQL Free Source Code
  5. News Portal Project in PHP and MySql Free Source Code
  6. User Login & Registration System Using PHP and MySQL Free Code
  7. Top 10 Final Year Project Ideas in Python
  8. Online Bike Rental Management System Using PHP and MySQL
  9. E learning Website in php with Free source code
  10. E-Commerce Website Project in Java Servlets (JSP)
  • AI
  • ASP.NET
  • Blockchain
  • ChatCPT
  • code Snippets
  • Collage Projects
  • Data Science Project
  • Data Science Tutorial
  • DBMS Tutorial
  • Deep Learning Tutorial
  • Final Year Projects
  • Free Projects
  • How to
  • html
  • Interview Question
  • Java Notes
  • Java Project
  • Java Script Notes
  • JAVASCRIPT
  • Javascript Project
  • JSP JAVA(J2EE)
  • Machine Learning Project
  • Machine Learning Tutorial
  • MySQL Tutorial
  • Node.js Tutorial
  • PHP Project
  • Portfolio
  • Python
  • Python Interview Question
  • Python Projects
  • PythonFreeProject
  • React Free Project
  • React Projects
  • Spring boot
  • SQL Tutorial
  • TOP 10
  • Uncategorized
  • Online Examination System in PHP with Source Code
  • AI Chatbot for College and Hospital
  • Job Portal Web Application in PHP MySQL
  • Online Tutorial Portal Site in PHP MySQL — Full Project with Source Code
  • Online Job Portal System in JSP Servlet MySQL

Most Viewed Posts

  • Top Large Language Models in 2025 (8,612)
  • Online Shopping System using PHP, MySQL with Free Source Code (5,210)
  • login form in php and mysql , Step-by-Step with Free Source Code (4,862)

Copyright © 2026 UpdateGadh.

Powered by PressBook Green WordPress theme