Python错误集锦:logging模块Formatter提示ValueError: incomplete format

原文链接:http://www.juzicode.com/python-error-logging-valueerror-incomplete-format/

错误提示:

使用logging.Formatter创建输出格式时,提示ValueError: incomplete format

#juzicode.com / vx:桔子code
import logging
logger = logging.getLogger('logtop')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s - %(lineno)d - %(message)')
cons_handler = logging.StreamHandler()
cons_handler.setLevel(logging.INFO)  
cons_handler.setFormatter(formatter)
logger.addHandler(cons_handler)
logger.info('juzicode.com / vx:桔子code')  
==========运行结果:
--- Logging error ---
Traceback (most recent call last):
  File "D:\Python\Python38\lib\logging\__init__.py", line 1081, in emit
    msg = self.format(record)
  File "D:\Python\Python38\lib\logging\__init__.py", line 925, in format
    return fmt.format(record)
  File "D:\Python\Python38\lib\logging\__init__.py", line 667, in format
    s = self.formatMessage(record)
  File "D:\Python\Python38\lib\logging\__init__.py", line 636, in formatMessage
    return self._style.format(record)
  File "D:\Python\Python38\lib\logging\__init__.py", line 436, in format
    return self._format(record)
  File "D:\Python\Python38\lib\logging\__init__.py", line 432, in _format
    return self._fmt % record.__dict__
ValueError: incomplete format
Call stack:
  File "error.py", line 10, in 
    logger.info('juzicode.com / vx:桔子code')
Message: 'juzicode.com / vx:桔子code'
Arguments: ()

 

错误原因:

1、使用logging.Formatter(‘% (name)s – %(lineno)d – %(message)’)设置格式时,“%(message)”最后缺少格式化方法

 

解决方法:

1、补齐message的格式化方法:logging.Formatter(‘% (name)s – %(lineno)d – %(message)’)修改为logging.Formatter(‘% (name)s – %(lineno)d – %(message)s’)

#juzicode.com / vx:桔子code
import logging
logger = logging.getLogger('logtop')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(name)s - %(lineno)d - %(message)s')
cons_handler = logging.StreamHandler()
cons_handler.setLevel(logging.INFO)  
cons_handler.setFormatter(formatter)
logger.addHandler(cons_handler)
logger.info('juzicode.com / vx:桔子code')  
==========运行结果:
logtop - 10 - juzicode.com / vx:桔子code

 


 

如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注