我尝试创建日志时出现不受支持的格式字符'%'错误

时间:2019-10-08 07:04:22

标签: python logging

我正在尝试使用以下代码创建一个简单的日志文件。

import logging

format = '%(asctime) %(message)'

logging.basicConfig(format=format)
log_message = {'service': 'test-service', 'm': 'service started successfuly!'}
logger = logging.getLogger('root-logger')

logger.warning('this is a test log message %s', extra = log_message)

但是当我尝试执行以上代码时,出现一条错误消息:

    --- Logging error ---
Traceback (most recent call last):
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 1025, in emit
    msg = self.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 869, in format
    return fmt.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 611, in format
    s = self.formatMessage(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 580, in formatMessage
    return self._style.format(record)
File "/Users/pc/anaconda3/envs/spider/lib/python3.7/logging/__init__.py", line 422, in format
    return self._fmt % record.__dict__
ValueError: unsupported format character '%' (0x25) at index 11
Call stack:
File "test.py", line 9, in <module>
    logger.warning('this is a test log message %s', extra = log_message)
Message: 'this is a test log message %s'
Arguments: ()

我无法理解该错误。此错误的原因可能是什么?

2 个答案:

答案 0 :(得分:2)

有两个问题:

1)您的格式字符串在s之后缺少%(...)

2)您的日志记录调用缺少与%s对应的必需参数

尝试一下:

import logging

format = '%(asctime)s %(message)s'

logging.basicConfig(format=format)
log_message = {'service': 'test-service', 'm': 'service started successfuly!'}
logger = logging.getLogger('root-logger')

logger.warning('this is a test log message %s', 'msg', extra=log_message)

这将打印

2019-10-08 12:45:28,991 this is a test log message msg

那么您的extra怎么了?嗯,您的格式没有放置它们的位置,因此它们没有出现。要显示额外的数据,格式化程序必须在字典中的每个键

中保留位置
format = '%(asctime)s %(message)s | %(service)s - %(m)s'

将打印:

2019-10-08 12:50:30,189 this is a test log message msg | test-service - service started successfuly!

以下是相关文档:https://docs.python.org/3/library/logging.html#logging.Logger.debug

答案 1 :(得分:1)

“%s”表示期望将字符串作为位置参数。因此,您应该提供一个字符串来替代“%s”:

logger.warning('this is a test log message %s', 'service started successfully!')

下面是一个示例,如果您想使用“额外”:

import logging

# "service" and "m" are extra arguments so you need
# to supply them inside the "extra" dictionary with every log entry.
format = '%(asctime)s %(service)s %(m)s %(message)s'
# (Note the "s" after the brackets that specify a string)

logging.basicConfig(format=format)
log_message = {'service': 'test-service', 'm': 'service started successfuly!'}
logger = logging.getLogger('root-logger')

logger.warning('this is a test log message', extra=log_message)

结果:

2019-10-08 10:19:00,310 test-service service started successfully! this is a test log message