Python 日志记录 logging

logging 是 Python 的标准日志模块,比 print 更专业。

1. 基本用法

import logging

# 设置级别
logging.basicConfig(level=logging.DEBUG)

logging.debug('Debug message')
logging.info('Info message')
logging.warning('Warning message')
logging.error('Error message')
logging.critical('Critical message')

2. 配置日志文件

import logging

logging.basicConfig(
    filename='app.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

3. 使用 Logger

import logging

logger = logging.getLogger(__name__)

logger.debug('Debug')
logger.info('Info')
logger.warning('Warning')

4. 格式化

logging.basicConfig(
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)

5. 不同级别处理器

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# 控制台输出
console = logging.StreamHandler()
console.setLevel(logging.INFO)

# 文件输出
file = logging.FileHandler('app.log')
file.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(message)s')
console.setFormatter(formatter)
file.setFormatter(formatter)

logger.addHandler(console)
logger.addHandler(file)

日志是调试和监控应用的重要工具。