search
HomeBackend DevelopmentPython TutorialPython logging module: The definitive guide from beginner to proficient

Python logging 模块:从入门到精通的权威指南

python logging, recording, application Log, log level, log format

introduction

Logging is a crucial aspect of software development, enabling you to record application events, errors, and debugging information. Python The logging module provides a comprehensive framework for handling log messages of varying severity and writing them to various destinations. By following the steps in this article, you will master every aspect of the logging module and learn to use it effectively to improve the quality of your application.

Installation and Configuration

To use the logging module, make sure your Python environment has it installed. If you haven't installed it yet, install it using pip:

pip install logging

After completing the installation, you need to configure it. You can configure it by creating a logging.conf file in project or directly in code.

Log level

The logging module supports five predefined log levels:

  • DEBUG
  • INFO
  • WARNING
  • ERROR
  • CRITICAL

Each level represents the severity of the log message, DEBUG is the lowest and CRITICAL is the highest. You can select the appropriate level based on the level of information you need to log.

Logger

The logger object is the core of the logging module. It is responsible for generating and processing log messages. You can create a logger using the logging.getLogger() function. It accepts a name parameter that identifies the logger.

Log handler

Log handlers are objects that write log messages to different destinations. The logging module provides a variety of built-in handlers, such as:

  • StreamHandler: Write log messages to standard output or standard error.
  • FileHandler: Write log messages to a file.
  • SMTPHandler: Send log messages via email.

You can add multiple handlers to the logger as needed.

Log format

You can customize the format of log messages. The logging module provides the logging.F<strong class="keylink">ORM</strong>atter class for specifying the layout of log messages. It accepts the following parameters:

  • fmt: Format of log message String.
  • datefmt: Format string for date and time.

Example:

The following example demonstrates how to configure and use the logging module:

import logging

# 创建一个 logger。
logger = logging.getLogger(__name__)

# 设置日志级别。
logger.setLevel(logging.DEBUG)

# 创建一个流处理程序。
stream_handler = logging.StreamHandler()

# 创建一个文件处理程序。
file_handler = logging.FileHandler("app.log")

# 设置日志格式。
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
stream_handler.setFormatter(formatter)
file_handler.setFormatter(formatter)

# 将处理程序添加到 logger。
logger.addHandler(stream_handler)
logger.addHandler(file_handler)

# 记录日志消息。
logger.debug("这是一个调试消息。")
logger.info("这是一个信息消息。")
logger.warning("这是一个警告消息。")
logger.error("这是一个错误消息。")
logger.critical("这是一个致命错误消息。")

Other functions

The logging module also provides some other functions, such as:

  • Filter: Used to filter log messages.
  • Exception catching: Exceptions can be caught and logged as log messages.
  • Handler chain: Multiple handlers can be chained together to form a chain of log message processing.

Best Practices

When using the logging module, follow these best practices:

  • Use meaningful log messages.
  • Select the appropriate log level based on severity.
  • Limit log messages to useful information.
  • Configure log handlers and formats carefully.
  • Advanced logging using filters and handler chains.

in conclusion

By mastering the Python logging module, you can effectively record and process application logs. It can help you debug problems, monitor application performance, and enhance the overall robustness of your application. This article provides a comprehensive guide from Getting Started to Mastery, allowing you to take full advantage of the power of this module.

The above is the detailed content of Python logging module: The definitive guide from beginner to proficient. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:编程网. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor