Skip to content Skip to sidebar Skip to footer

Optional Keys In String Formats Using '%' Operator?

Is is possible to have optional keys in string formats using '%' operator? I’m using the logging API with Python 2.7, so I can't use Advanced String Formatting. My problem is as

Solution 1:

A) The defaultdict approach works fine, but only if used directly.

>>>import collections>>>dd=collections.defaultdict(str)>>>dd['k'] = 22>>>'%(k)s %(nn)s' % dd
'22 '

B) The extra argument to a log function is used as described in the docs, i.e. not directly as shown above. That's why using a defaultdict instead of a regular dict does not make a difference.

The third keyword argument is extra which can be used to pass a dictionary which is used to populate the dict of the LogRecord created for the logging event with user-defined attributes.


C) You can use a logging filter to take care of the missing extra data:

import logging

classUserFilter:
    deffilter(self, record):
        try:
            record.user
        except AttributeError:
            record.user = '<N/A>'returnTrue

FORMAT = '%(asctime)-15s %(message)s %(user)s'
logging.basicConfig(format=FORMAT)
logging.getLogger().addFilter(UserFilter())

logging.warning("It works for:", extra={'user': 'me'})

logging.warning("It doesn't work!")
# DATE TIME It doesn't work! <N/A>

Any class with a filter method is fine. It can modify the record in-place and it must return True for accepting the record or False for filtering it out.

Post a Comment for "Optional Keys In String Formats Using '%' Operator?"