(continued from previous page) 

return ' %s >>> %s '%(self.message, json .dumps( self.kwargs)) _ =StructuredMessage # optional, to improve readability logging.basicConfig(level =logging.INFO, format=' %(message)s ') logging.info(_( 'message 1', foo='bar', bar='baz', num =123 , fnum =123.456 )) 

If the above script is run, it prints: 

message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", 

Note that the order of items might be different according to the version of Python used. 

If you need more specialised processing, you can use a custom JSON encoder, as in the following complete example: 

from __future__ import unicode_literals import json import logging # This next bit is to ensure the script runs unchanged on 2.x and 3.x try : unicode except NameError: unicode =str classEncoder (json.JSONEncoder): def default(self, o): if isinstance(o,set): return tuple(o) elif isinstance(o, unicode): return o.encode('unicode_escape').decode('ascii') return super() .default(o) classStructuredMessage : def __init__ (self, message,/,**kwargs): self.message =message self.kwargs =kwargs def __str__ (self): s =Encoder() .encode(self.kwargs) return ' %s >>> %s '%(self.message, s) _ =StructuredMessage # optional, to improve readability def main(): logging.basicConfig(level =logging.INFO, format=' %(message)s ') logging.info(_( 'message 1', set_value ={ 1,2,3}, snowman =' \u2603 ')) if __name__ =='__main__ ': main() 

When the above script is run, it prints: 

message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]} 

Note that the order of items might be different according to the version of Python used. 

