如何在 Python 的单个日志记录中记录两个变量值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20780608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:13:38  来源:igfitidea点击:

How to log two variables values in a single logging in Python?

pythonlogging

提问by

I am working with Python and I need to use logger so I decided to start using RotatingFileHandler. Below is my logging.conffile

我正在使用 Python,我需要使用记录器,所以我决定开始使用 RotatingFileHandler。下面是我的logging.conf文件

[loggers]
keys=root

[handlers]
keys=logfile

[formatters]
keys=logfileformatter

[logger_root]
level=DEBUG
handlers=logfile

[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s

[handler_logfile]
class=handlers.RotatingFileHandler
level=NOTSET
args=('ookagent.log', 'a', 50000000000, 5)
formatter=logfileformatter

And below is my Python script from which I am successfully able to log to the files. But I am trying to log two variable values from a single logging as mentioned like below -

下面是我的 Python 脚本,我可以从中成功登录到文件。但是我试图从单个日志记录中记录两个变量值,如下所述 -

#!/usr/bin/python
import logging
import logging.config
import logging.handlers

# using RotatingFileHandler for logging purpose
logging.config.fileConfig('logging.conf')
ooklogger = logging.getLogger('')

list1 = ['abc', 'def', 'ghi']
list2 = ['jkl', 'mno', 'pqr']

ooklogger.info("Test %s" % (list1, list2))

But whenever I run my above Python script, I always get below error -

但是每当我运行上面的 Python 脚本时,我总是得到以下错误 -

ooklogger.info("Test %s" % (list1, list2))
TypeError: not all arguments converted during string formatting

Any idea what wrong I am doing?

知道我在做什么错吗?

回答by cjhanks

The python logging functions support a built-in string replacement documented here. This logging supports both arg and kwarg replacement.

python 日志记录函数支持内置的字符串替换记录在这里。此日志记录支持 arg 和 kwarg 替换。

from sys     import stderr
from logging import getLogger, StreamHandler, Formatter, DEBUG

l  = getLogger()
sh = StreamHandler(stderr)
sh.setLevel(DEBUG)
f  = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
sh.setFormatter(f)
l.addHandler(sh)
l.setLevel(DEBUG)

L0 = ['abc', 'def', 'ghi']
L1 = ['jkl', 'mno', 'pqr']

l.info('%(list_0)s - %(list_1)s', { 'list_0': L0, 'list_1' : L1 })
# identical to 
l.info('%s - %s', L0, L1)
# identical to 
l.info('%s - %s' % (L0, L1))