python-backend
/

Python Logging – Professional Debugging & Monitoring

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Python Logging – Professional Debugging & Monitoring

Why Use Logging Instead of Print?

As a Technical Lead, you know that print() is for development, but Logging is for production. When your Flutter backend is running on a remote server, you can't see the standard output. The logging module provides a flexible framework for emitting log messages from Python programs, allowing you to categorize events by severity and direct them to different destinations (files, consoles, or external monitoring services).

  1. Log Levels (Severity)

Logging levels allow you to filter the importance of the information being recorded. In production, you might only care about 'Error' and 'Critical', while in development, you want 'Debug' information.

LevelNumeric ValueUsage
DEBUG10Detailed info for diagnosing problems
INFO20Confirmation that things are working as expected
WARNING30Indication that something unexpected happened (Default)
ERROR40A more serious problem; the software couldn't perform a function
CRITICAL50A serious error; the program itself may be unable to continue

  1. The Logging Architecture

The logging flow involves three main objects: Loggers (the entry point), Handlers (where the log goes), and Formatters (how the log looks).

PythonRead-only
1
import logging

# Basic configuration
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    filename='app.log',
    filemode='a'
)

logger = logging.getLogger('ProjectManager')

logger.info("Initializing Revochamp AI Engine...")
try:
    # Simulate a failure
    1 / 0
except ZeroDivisionError:
    logger.error("Math error occurred", exc_info=True) # exc_info captures the stack trace

  1. Advanced Handlers

For enterprise applications, you don't want a single text file that grows to several gigabytes. You should use specialized handlers:

  • RotatingFileHandler: Automatically 'rolls over' the log file when it reaches a certain size.
  • TimedRotatingFileHandler: Rotates logs at specific time intervals (e.g., every midnight).
  • StreamHandler: Sends logs to the console (useful for Docker/Container logs).
  • SMTPHandler: Sends an email when a 'CRITICAL' error occurs.

Best Practices for Architecture

Always use __name__ when creating a logger: logger = logging.getLogger(__name__). This ensures the log message shows exactly which module produced the error, making debugging significantly easier in complex microservices.

Try it yourself

import logging
import sys

# Setup logger to output to console
logger = logging.getLogger('TestApp')
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(levelname)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

# Test the levels
logger.debug("This is a hidden detail")
logger.info("User logged in")
logger.warning("Disk space low")
logger.error("Database connection failed")

Test Your Knowledge

Q1
of 3

What is the default logging level if not configured?

A
DEBUG
B
INFO
C
WARNING
D
ERROR
Q2
of 3

Which logging component determines the final string representation of the log message?

A
Logger
B
Handler
C
Filter
D
Formatter
Q3
of 3

Why is logging.basicConfig() usually called only once?

A
It consumes too much memory
B
It sets the global configuration for the root logger
C
It locks the database
D
It is a Python syntax rule

Frequently Asked Questions

What is 'exc_info=True'?

When an exception occurs, passing 'exc_info=True' to a logger method (like logger.error) will automatically append the full stack trace to the log message. This is vital for finding the line of code that caused the crash.

Can I log to multiple places at once?

Yes. You can add multiple handlers to a single logger. For example, you can send 'INFO' logs to the console and 'ERROR' logs to a persistent file or an external service like Sentry.

How do I stop third-party libraries from flooding my logs?

You can set the level for specific loggers. For example: 'logging.getLogger("requests").setLevel(logging.WARNING)' will hide all DEBUG and INFO messages from the requests library.

Previous

python deployment

Next

python best practices

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.