python - Optional keys in string formats using '%' operator? -


is possible have optional keys in string formats using '%' operator? i’m using logging api python 2.7, can't use advanced string formatting.

my problem follow:

>>> import logging  >>> format = '%(asctime)-15s %(message)s %(user)s' >>> logging.basicconfig(format=format)  >>> logging.warning("it works for:", extra={'user': 'me'}) 2016-08-29 11:24:31,262 works for: me  >>> logging.warning("it does't work!") traceback (most recent call last):   ... keyerror: 'user' logged file <input>, line 1 

i want have empty string user if missing. how can that?

i tried defaultdict, fails:

>>> import collections >>> = collections.defaultdict(unicode) >>> logging.warning("it does't work!", extra=extra) traceback (most recent call last):   ... keyerror: 'user' logged file <input>, line 1 

by contrast, jinja2, can do:

>>> import jinja2 >>> jinja2.template('name: {{ name }}, email: {{ email }}').render(name="me") u'name: me, email: ' 

=> no exception here, empty string (for "email").

a) defaultdict approach works fine, if used directly.

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

b) extra argument log function used described in docs, i.e. not directly shown above. that's why using defaultdict instead of regular dict not make difference.

the third keyword argument can used pass dictionary used populate dict of logrecord created logging event user-defined attributes.


c) can use logging filter take care of missing data:

import logging  class userfilter:     def filter(self, record):         try:             record.user         except attributeerror:             record.user = '<n/a>'         return true  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 doesn't work! <n/a> 

any class filter method fine. can modify record in-place , must return true accepting record or false filtering out.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -