Python错误集锦:使用logging.Formatter()创建格式时提示TypeError: not enough arguments for format string

原文链接: http://www.juzicode.com/python-error-logging-formatter-typeerror-not-enough-arguments/

错误提示:

 使用logging.Formatter()创建格式时提示TypeError: not enough arguments for format string

import logging

#创建logger实例
logger = logging.getLogger('logtop')
#设置logger实例的等级
logger.setLevel(logging.ERROR)
#创建formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - % (lineno)d - %(levelname)s - %(message)s')
#创建控制台handler
cons_handler = logging.StreamHandler()
cons_handler.setLevel(logging.INFO) 
cons_handler.setFormatter(formatter)#添加handler到logger
logger.addHandler(cons_handler)
#这里用logger实例输出日志
logger.critical('这是logging测试例子')  
logger.error('VX:桔子code')  
logger.warning('www.juzicode.com')  
logger.info('are you kiding me?')    
logger.debug('i am serious!')    
==========运行结果:
--- 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__
TypeError: not enough arguments for format string
Call stack:
  File "logging-stdout-file.py", line 31, in < module>
    logger.critical('这是logging测试例子')
Message: '这是logging测试例子'
Arguments: ()

 

 

错误原因:

1、formatter = logging.Formatter(‘%(asctime)s – %(name)s – % (lineno)d – %(levelname)s – %(message)s’)格式不正确,在“% (lineno)d”的%后多了个空格

 

解决方法:

1、删除“% (lineno)d”的%后的空格

import logging

#创建logger实例
logger = logging.getLogger('logtop')
#设置logger实例的等级
logger.setLevel(logging.ERROR)
#创建formatter
#formatter = logging.Formatter('%(asctime)s - %(name)s - % (lineno)d - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s')
#创建控制台handler
cons_handler = logging.StreamHandler()
cons_handler.setLevel(logging.INFO) 
cons_handler.setFormatter(formatter)#添加handler到logger
logger.addHandler(cons_handler)
#这里用logger实例输出日志
logger.critical('这是logging测试例子')  
logger.error('VX:桔子code')  
logger.warning('www.juzicode.com')  
logger.info('are you kiding me?')    
logger.debug('i am serious!')    
==========运行结果:
2021-01-15 21:33:12,227 - logtop - 22 - CRITICAL - 这是logging测试例子
2021-01-15 21:33:12,227 - logtop - 23 - ERROR - VX:桔子code

 

扩展内容:

  1.  Python进阶教程m14–日志记录logging

 


 

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

发表评论

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