2025年07月31日/ 浏览 8
在软件开发的生命周期中,日志就像程序的”黑匣子”,记录着运行时的重要信息。作为Python开发者,掌握logging模块的深度用法,能让你在故障排查时事半功倍。
日志级别金字塔
python
import logging
logging.basicConfig(level=logging.DEBUG) # 设置捕获的最低级别
级别从低到高分为:DEBUG → INFO → WARNING → ERROR → CRITICAL。实际项目中建议开发环境用DEBUG,生产环境用INFO以上级别。
格式化输出艺术
python
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
常用占位符包括:
%(lineno)d
:调用行号%(pathname)s
:完整路径%(module)s
:模块名输出渠道多元化
python
console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('app.log')
console_handler.setLevel(logging.WARNING) # 控制台只显示警告以上
大型项目中常遇到日志混乱的问题,正确的做法是:
python
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
sub_logger = logging.getLogger(f'{name}.submodule’)
通过getLogger
创建的logger会形成继承关系,子模块自动继承父模块的配置,避免重复设置。
日志文件自动分割
python
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler(
'app.log', maxBytes=5*1024*1024, backupCount=3
)
当文件超过5MB会自动创建新文件,保留最近3个备份。
敏感信息过滤
python
class SecurityFilter(logging.Filter):
def filter(self, record):
record.msg = record.msg.replace('password=123', 'password=***')
return True
logger.addFilter(SecurityFilter())
跨时区时间处理
python
import pytz
class UTCFormatter(logging.Formatter):
converter = lambda x: x.astimezone(pytz.utc)
配置字典化(Python 3.2+)
python
config = {
'version': 1,
'formatters': {
'detailed': {
'format': '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
}
}
}
logging.config.dictConfig(config)
性能优化要点
logger.isEnabledFor(logging.DEBUG)
判断logging.handlers.QueueHandler
实现异步日志与第三方服务集成
python
from logging.handlers import SysLogHandler
syslog = SysLogHandler(address=('logs.papertrailapp.com', 12345))
日志重复输出问题
logger.propagate = False
阻断传播日志丢失排查
flush=True
)性能监控集成
python
statsd_handler = StatsDHandler(host='localhost', port=8125)
logger.addHandler(statsd_handler)
通过合理配置logging模块,我们不仅能记录程序运行状态,还能通过日志分析用户行为、监控系统性能。记住:好的日志系统不是事后排查的工具,而是系统设计的有机组成部分。
经验之谈:在微服务架构中,建议为每个服务分配唯一的日志标识符,并统一收集到ELK或Splunk等平台进行集中分析。