在Python中,logging模块提供了灵活的日志处理功能。以下是一些高级技巧:
basicConfig()方法可以配置日志级别(如DEBUG、INFO、WARNING、ERROR、CRITICAL)和日志格式(如时间戳、日志级别、消息、源代码文件名等)。import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') logging.Handler类创建自定义处理器,将日志消息写入文件、数据库或通过网络发送等。class FileHandler(logging.Handler): def __init__(self, filename): super().__init__() self.filename = filename def emit(self, record): with open(self.filename, 'a') as f: f.write(self.format(record) + '\n') logging.Filter类为日志消息添加过滤器,只输出符合特定条件的消息。class MyFilter(logging.Filter): def filter(self, record): return 'my_keyword' in record.getMessage() logger = logging.getLogger(__name__) logger.addFilter(MyFilter()) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler()])将日志记录到控制台。使用logging.captureWarnings(True)捕获Python的警告消息。使用logging.setLogRecordFactory(MyLogRecord)自定义日志记录器的记录格式。使用logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')自定义日志记录器的格式。使用logging.root.addHandler(my_handler)将自定义处理器添加到根记录器。使用logging.root.removeHandler(my_handler)删除自定义处理器。使用logging.root.setLevel(logging.DEBUG)设置根记录器的日志级别。使用logging.root.propagate(False)阻止日志消息向上级记录器传播。使用logging.captureWarnings(True)捕获Python的警告消息。