0

I am trying to add a dynamic string to a formatter but unable to do so.

Here is the code.

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('spam.log')

var = 'some vaue'
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s %s' % var)
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.error('error message')

Output:

Traceback (most recent call last):
  File "try.py", line 8, in <module>
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s %s' % var)
TypeError: format requires a mapping

here

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s %s' % var)

is what causing the error, i really need to add a varible var to this format.

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s simple_example')

works fine.

1 Answer 1

1

This will work

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s {0}'.format(var))

You can learn more here http://docs.python.org/2/library/string.html#format-examples

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it work. Please remove 'simple_example' from your answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.