user2467545
user2467545

Reputation:

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

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

[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 -

#!/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 -

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

Any idea what wrong I am doing?

Upvotes: 22

Views: 53271

Answers (2)

sha
sha

Reputation: 71

import logging
logging.info("str1: %s, str2: %s", "string1", "string2")

Upvotes: 7

cjhanks
cjhanks

Reputation: 544

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

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))

Upvotes: 33

Related Questions