Python 日志记录 - 在“记录”中覆盖 args/msg,以避免更改为可变对象数据

有没有办法用密文类实现Python日志记录过滤器,这样任何用参数记录消息的调用(例如,LOGGER.debug('my message, %s, %s', data1, data2)都使用msg和args的副本而不是传递的可变对象?我们的实现意味着日志记录编校类最终会更改可变数据,然后与编校字符串一起存储/发送可变数据。我知道我们可以在对记录器的调用上执行此操作,例如 LOGGER.debug('my message, %s, %s', copy.deepcopy(data1), copy.deepcopy(data2)),但希望有一种方法可以覆盖日志记录设置定义中“记录”的筛选器函数 resposnbile?


哆啦的时光机
浏览 152回答 1
1回答

智慧大石

您必须覆盖该函数。应用筛选器时,记录已创建。makeRecordimport loggingimport copyclass CopyLogger(logging.Logger):&nbsp; &nbsp; def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):&nbsp; &nbsp; &nbsp; &nbsp; args = copy.deepcopy(args) # <- this is the line you care about&nbsp; &nbsp; &nbsp; &nbsp; return super().makeRecord(name, level, fn, lno, msg, args, exc_info, func, extra, sinfo)logging.setLoggerClass(CopyLogger)log = logging.getLogger('mylogger')data1 = 'hello'data2 = 'world'log.warning('my message, %s, %s', data1, data2)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python