gpt4 book ai didi

python 在logging.debug()之后如何查看其日志记录

转载 作者:太空宇宙 更新时间:2023-11-03 20:32:14 25 4
gpt4 key购买 nike

最近我遇到了用 python 进行日志记录的情况。

我在 test.py 文件中有以下代码

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger.debug("test Message")

现在,有什么方法可以打印由 logger.debug("test Message") 生成的 Logrecord 对象,因为文档中指出

LogRecord instances are created automatically by the Logger every time something is logged

https://docs.python.org/3/library/logging.html#logrecord-objects

我检查了将debug保存到变量中并打印它

test = logger.debug("test Message")
print(test)

输出为NONE

我的目标是使用 print() 在同一个 test.py 中检查/查看由 logging.debug(test.py) 生成的最终 Logrecord 对象。这是我自己的理解。

print(LogrecordObject.__dict__)

那么如何获取由logger.debug("test Message")生成的Logrecord对象

最佳答案

debug()中没有返回

# Here is the snippet for the source code
def debug(self, msg, *args, **kwargs):
if self.isEnabledFor(DEBUG):
self._log(DEBUG, msg, args, **kwargs)

如果你想得到LogRecord返回,你需要重新定义debug() ,你可以这样覆盖:

import logging

DEBUG_LEVELV_NUM = 9
logging.addLevelName(DEBUG_LEVELV_NUM, "MY_DEBUG")

def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
sinfo = None
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if isinstance(exc_info, BaseException):
exc_info = (type(exc_info), exc_info, exc_info.__traceback__)
elif not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
record = self.makeRecord(self.name, level, fn, lno, msg, args,
exc_info, func, extra, sinfo)
self.handle(record)
return record


def my_debug(self, message, *args, **kws):
if self.isEnabledFor(DEBUG_LEVELV_NUM):
# Yes, logger takes its '*args' as 'args'.
record = self._log(DEBUG_LEVELV_NUM, message, args, **kws)
return record

logger = logging.getLogger(__name__)
logging.Logger.my_debug = my_debug
logging.Logger._log = _log
logger.setLevel(DEBUG_LEVELV_NUM)
logger.addHandler(logging.StreamHandler())
test = logger.my_debug('test custom debug')
print(test)

引用: How to add a custom loglevel to Python's logging facility

关于python 在logging.debug()之后如何查看其日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57420008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com