惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
月光博客
月光博客
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
Hugging Face - Blog
Hugging Face - Blog
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
F
Fortinet All Blogs
小众软件
小众软件
D
Docker
U
Unit 42
博客园 - 聂微东
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
云风的 BLOG
云风的 BLOG
博客园 - 司徒正美
有赞技术团队
有赞技术团队
腾讯CDC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Python Logging Levels
Maksym · 2026-05-18 · via DEV Community
Cover image for Python Logging Levels

Maksym

Python’s standard logging library uses a numeric severity system to filter log messages.

When you set a log level on a logger, you define a threshold: the logger will discard any message with a severity below this threshold and only process messages at or above it.


1. The 5 Standard Log Levels

Level Numeric Value When to Use It Example Scenario
CRITICAL 50 Severe errors that halt a core process or crash the app. Requires immediate intervention. Out of memory, database connection lost, disk full.
ERROR 40 Serious problems where the app failed to perform a specific function but can continue running. External API request timed out, file write failed.
WARNING 30 Default Level. Indicates something unexpected happened, or a potential problem is imminent. Low disk space, deprecated library usage, bad login attempt.
INFO 20 General operational events confirming that things are working as expected. "Successfully connected to database", "Kafka consumer started".
DEBUG 10 Detailed diagnostic information, useful during local development and troubleshooting. "Query returned 4 rows", "Received payload: {...}".
NOTSET 0 Default for non-root loggers. Inherits the level from its parent logger. Directs child loggers to rely on parent configuration.

2. How Level Filtering Works

When a log message is generated, Python compares its numeric value against the active logger's threshold:

Message Level (e.g., INFO = 20) >= Logger Threshold (e.g., WARNING = 30)?

20 >= 30  ---> FALSE (Log is silently discarded)
40 >= 30  ---> TRUE  (Log is processed and printed)

Enter fullscreen mode Exit fullscreen mode


3. Self-Contained Code Example

import logging

# Configure root logger to output INFO (20) and above
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# This will NOT print (DEBUG 10 < INFO 20)
logger.debug("Parsing payload dictionary...") 

# This WILL print (INFO 20 >= INFO 20)
logger.info("Successfully connected to the database.")

# This WILL print (ERROR 40 >= INFO 20)
logger.error("Failed to fetch profiles from downstream service.")

Enter fullscreen mode Exit fullscreen mode


4. The Hierarchy Gotcha: Level Inheritance

By default, the Root logger is initialized to WARNING (30).

Non-root (named) loggers inherit their level from their closest ancestor that has an explicit level set.

The Silent Log Trap:

import logging

# 1. No global config is set (Root defaults to WARNING)
logger = logging.getLogger("app.database")

# 2. You try to log an INFO message
logger.info("Connecting...")  # NOTHING PRINTS!

Enter fullscreen mode Exit fullscreen mode


5. Best Practice: Dynamic Environment Configuration

In containerized microservices (e.g., Docker, Kubernetes), you should never hardcode log levels.

Instead, read the level dynamically from an environment variable with a safe default.

import os
import logging

# 1. Fetch level from env variable, default to 'INFO' if not set
env_level = os.getenv("LOG_LEVEL", "INFO").upper()

# 2. Convert string level to numeric value safely
numeric_level = getattr(logging, env_level, logging.INFO)

# 3. Configure the Root baseline
logging.basicConfig(
    level=numeric_level,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

logger = logging.getLogger("app.service")
logger.info(f"Logger initialized with level: {env_level}")

Enter fullscreen mode Exit fullscreen mode


6. Environment Recommendations

  • Development (DEBUG):

    Set LOG_LEVEL=DEBUG. Helps trace raw incoming database queries, inspect message payloads, and track API states.

  • Production (INFO or WARNING):

    Set LOG_LEVEL=INFO. High-frequency DEBUG logging writes massive amounts of data to stdout, which can:

    • Exhaust server disk space
    • Overwhelm aggregation engines (Elasticsearch, Grafana Loki, Splunk)
    • Degrade application I/O performance