Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Logging Tutorial – Complete Guide with Examples

Python - Logging 

When building real-world Python applications, simply using print() statements is not enough to track what is happening inside your program. You need a more powerful and professional way to record events, errors, and system behavior.

This is where Logging in Python becomes extremely useful.

Python provides a built-in module called logging, which helps developers track events that happen while a program runs. It is widely used in debugging, monitoring applications, and production systems.

In this tutorial, you will learn what logging is, why it is important, how to use it, different log levels, formatting logs, and real-world examples.


What is Logging in Python?

Logging is the process of recording messages that describe what is happening in a program.

Instead of printing messages manually, logging allows you to:

  • Track program flow
  • Record errors and warnings
  • Debug issues easily
  • Store logs in files
  • Monitor applications in production

Why Use Logging Instead of print()?

print()Logging
Used for simple outputUsed for real applications
Cannot categorize messagesSupports log levels
Not saved automaticallyCan save logs to files
Hard to manage in large appsHighly structured system

Logging is essential for professional software development.


Importing Logging Module

import logging

This module is built into Python, so no installation is required.


Basic Logging Example

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Debug message")
logging.info("Information message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")

Output Example

WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical message

By default, Python shows only warnings and above unless configured.


Logging Levels in Python

Python provides five main logging levels:

LevelDescription
DEBUGDetailed information for debugging
INFOGeneral program information
WARNINGSomething unexpected happened
ERRORA serious problem occurred
CRITICALVery severe error

Setting Log Level

import logging

logging.basicConfig(level=logging.INFO)

logging.info("App started")
logging.warning("Low memory warning")

Only INFO and above messages will be shown.


Logging to a File

Instead of printing logs on screen, you can save them into a file.

import logging

logging.basicConfig(
    filename="app.log",
    level=logging.DEBUG,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("Application started")
logging.error("An error occurred")

Log File Output Example

2026-06-08 10:15:30 - INFO - Application started
2026-06-08 10:15:31 - ERROR - An error occurred

Custom Log Format

You can control how logs appear using format strings.

import logging

logging.basicConfig(
    format="%(levelname)s - %(message)s",
    level=logging.DEBUG
)

logging.warning("This is a warning")

Adding Timestamp in Logs

import logging

logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(message)s",
    level=logging.DEBUG
)

logging.info("System running")

Real-Life Example: Bank System

import logging

logging.basicConfig(level=logging.INFO)

balance = 1000
withdraw = 500

logging.info("Transaction started")

if withdraw > balance:
    logging.error("Insufficient funds")
else:
    balance -= withdraw
    logging.info("Withdrawal successful")

Logging Exceptions

Logging is very useful for capturing errors.

import logging

logging.basicConfig(level=logging.ERROR)

try:
    result = 10 / 0
except Exception as e:
    logging.error("An exception occurred: %s", e)

Logging Stack Trace (Advanced)

To capture full error details:

import logging

logging.basicConfig(level=logging.ERROR)

try:
    int("abc")
except Exception:
    logging.exception("Exception occurred")

This automatically includes stack trace information.


Logging to Console and File

import logging

logging.basicConfig(
    level=logging.DEBUG,
    handlers=[
        logging.FileHandler("app.log"),
        logging.StreamHandler()
    ],
    format="%(asctime)s - %(levelname)s - %(message)s"
)

logging.info("Logging to file and console")

Creating a Logger Object

For large applications, it is better to create custom loggers.

import logging

logger = logging.getLogger("MyApp")
logger.setLevel(logging.DEBUG)

logger.info("Custom logger message")

Real-World Applications of Logging

Logging is used in:

  • Web applications (Django, Flask)
  • APIs and backend services
  • Banking systems
  • Data pipelines
  • Machine learning training logs
  • Cloud monitoring systems
  • Mobile backend systems

Best Practices

1. Always Use Logging in Production

Never rely on print() for real applications.


2. Use Proper Log Levels

  • DEBUG → development
  • INFO → normal operations
  • WARNING → potential issues
  • ERROR → failures
  • CRITICAL → system failure

3. Log Important Events Only

Avoid logging unnecessary data.


4. Use File Logging for Applications

Store logs for debugging and monitoring.


5. Avoid Sensitive Data

Never log passwords or private information.


Common Mistakes

Using print Instead of Logging

Bad:

print("Error occurred")

Good:

logging.error("Error occurred")

Not Setting Log Levels

Without levels, logs become messy and hard to manage.


Logging Too Much Data

Too many logs can slow down performance.


Summary

Logging in Python is a powerful feature that helps developers track, debug, and monitor applications efficiently. It is far better than using print statements and is essential for professional software development.

Key Takeaways

  • Logging records program events and errors
  • Python provides a built-in logging module
  • Log levels include DEBUG, INFO, WARNING, ERROR, CRITICAL
  • Logs can be saved to files or shown in console
  • Logging improves debugging and application monitoring
  • Always use logging in production systems

Mastering logging will help you build more professional, maintainable, and scalable Python applications.




Post a Comment

0 Comments