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

Ama*_*nda 5 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)
Run Code Online (Sandbox Code Playgroud)

但是当我尝试执行上面的代码时,我收到一条错误消息:

    --- 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: ()
Run Code Online (Sandbox Code Playgroud)

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

rda*_*das 6

有两个问题:

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)
Run Code Online (Sandbox Code Playgroud)

这将打印

2019-10-08 12:45:28,991 this is a test log message msg
Run Code Online (Sandbox Code Playgroud)

那么你的怎么了extra?那么你的格式没有任何地方可以放置它们,所以它们没有出现。为了让你的额外数据显示出来,你的格式化程序必须在字典中为每个键都有位置

format = '%(asctime)s %(message)s | %(service)s - %(m)s'
Run Code Online (Sandbox Code Playgroud)

将打印:

2019-10-08 12:50:30,189 this is a test log message msg | test-service - service started successfuly!
Run Code Online (Sandbox Code Playgroud)

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