我一直在尝试通过以下两个优秀帖子添加自定义日志级别:
How to add a custom loglevel to Python's logging facility
在我的顶级__init__.py中我放了:
import logging
logging.VERBOSE = 15
logging.addLevelName(logging.VERBOSE, "VERBOSE")
def verbose(self, message, *args, **kws):
if self.isEnabledFor(logging.VERBOSE):
# Yes, logger takes its '*args' as 'args'.
self._log(logging.VERBOSE, message, args, **kws)
setattr(logging, 'verbose', verbose)
setattr(logging.Logger, 'verbose',verbose)
#also tried
# logging.Logger.verbose=verbose
# logging.verbose=verbose
logging.getLogger(__name__).addHandler(logging.NullHandler())
在各种其他类和子模块中,我期待我可以:
import logging
.
.
.
logging.verbose("Someone sent us up the bomb")
但是,所有这些让我:
TypeError: verbose() missing 1 required positional argument: 'message'
如果我切换到:
logging.log(logging.VERBOSE, "Intent Returned: " + intent_name)
我没有抛出异常,但我也没有打印任何消息。
自我是阻止这种工作的原因,因为看起来你不是在课堂上操作。
如果您使用的是Basic Config,可以在__init__.py
或__main__.py
中以这种方式添加自定义级别:
import logging
log_level = 15
logging.basicConfig(
level=int(log_level),
format="%(asctime)s [%(threadName)-12.12s] [%(levelname)-7.7s] %(message)s",
handlers=[
logging.FileHandler('put your log path here'),
logging.StreamHandler()
]
)
def verbose(msg, *args, **kwargs):
if logging.getLogger().isEnabledFor(15):
logging.log(15, msg)
logging.addLevelName(15, "VERBOSE")
logging.verbose = verbose
logging.Logger.verbose = verbose
# now try the new level
logging.verbose("This is verbose logging")
如果您在所有文件中使用标准记录器,这也适用于其他文件。