import logging # 创建一个日志记录器 logger = logging.getLogger(__name__)
logger.info("这是信息消息") logger.warning("这是警告消息") logger.error("这是错误消息")
# 设置根日志记录器的级别为 INFO logging.basicConfig(level=logging.INFO) # 设置特定日志记录器的级别为 DEBUG logging.getLogger("mymodule").setLevel(logging.DEBUG)
# 将日志记录输出到名为 "mylog.txt" 的文件 logging.basicConfig(filename="mylog.txt")
# 自定义日志记录格式 logging.basicConfig(fORMat="%(asctime)s %(levelname)s:%(message)s")
# 创建一个文件处理程序和一个控制台处理程序 file_handler = logging.FileHandler("mylog.txt") console_handler = logging.StreamHandler() # 将处理程序添加到日志记录器 logger.addHandler(file_handler) logger.addHandler(console_handler)
import logging # 创建一个自定义处理程序 class MyHandler(logging.Handler): def emit(self, record): # 自定义处理记录的方式 # 添加自定义处理程序到日志记录器 logger.addHandler(MyHandler())
import logging # 创建一个过滤 filter = logging.Filter("mymodule") # 将过滤添加到处理程序 handler.addFilter(filter)
python The logging module provides powerful functionality to help you track, log, and debug the health of your application. By understanding the basic concepts and advanced techniques described in this article, you can effectively configure logging and create custom solutions tailored to your specific needs.
The above is the detailed content of Python logging module: The ultimate question-answering guide. For more information, please follow other related articles on the PHP Chinese website!