Home >Backend Development >Python Tutorial >Python logging module knowledge points revealed: common questions all in one place
The basic principle of the logging module is to create a logger (logger) and then record messages by calling the logger method. A logger has a level that determines which messages will be logged. The logging module defines several predefined levels, including DEBUG, INFO, WARNING, ERROR, and CRITICAL.
import logging # 创建一个名为 "my_logger" 的记录器,并设置其级别为 INFO logger = logging.getLogger("my_logger") logger.setLevel(logging.INFO)
A logger can log messages through its methods:
# 记录一条 INFO 级别的消息 logger.info("This is an INFO message") # 记录一条 WARNING 级别的消息 logger.warning("This is a WARNING message") # 记录一条 ERROR 级别的消息 logger.error("This is an ERROR message")
The log handler (handler) writes log messages to a specific destination, such as the console, file, or Networkserver. The logging module provides several predefined handlers:
# 创建一个控制台处理程序 handler = logging.StreamHandler() # 创建一个文件处理程序,将日志写入文件 "my_log.txt" handler = logging.FileHandler("my_log.txt")
Handlers can be attached to the logger by adding to the logger:
# 将处理程序添加到记录器 logger.addHandler(handler)
The log formatter (fORMatter) controls the appearance of log messages. The logging module provides several predefined formatters:
# 创建一个基本格式器 formatter = logging.BasicFormatter() # 使用自定义格式字符串创建自定义格式器 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
Formatters can be attached to handlers by adding to the handler:
# 将格式器添加到处理程序 handler.setFormatter(formatter)
1. How to set logging level in Python script?
import logging # 设置根日志记录器的级别为 INFO logging.basicConfig(level=logging.INFO)
2. How to log exceptions?
try: # 尝试执行一些代码 except Exception as e: # 记录异常 logger.error(e, exc_info=True)
3. How to disable a specific handler?
# 禁用控制台处理程序 logger.removeHandler(handler)
4. How to use custom log format?
# 使用自定义格式字符串创建自定义格式器 formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # 将格式器添加到处理程序 handler.setFormatter(formatter)
5. How to catch uncaught exceptions and log them to a file?
import sys import logging def exception_handler(type, value, traceback): # 记录未捕获的异常 logger.error(value, exc_info=(type, value, traceback)) sys.excepthook = exception_handler
Python The logging module is a powerful tool that can help you easily log and process application messages. By mastering its key points, you can effectively use the logging module to debug, troubleshoot, and analyze the behavior of your application.
The above is the detailed content of Python logging module knowledge points revealed: common questions all in one place. For more information, please follow other related articles on the PHP Chinese website!