I want to use pprint's output to show a complex data structure, but I would like to output it using the logging module rather than stdout.
ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT
I want to use pprint's output to show a complex data structure, but I would like to output it using the logging module rather than stdout.
ds = [{'hello': 'there'}]
logging.debug( pprint.pprint(ds) ) # outputs as STDOUT
Use pprint.pformat
to get a string, and then send it to your logging framework.
from pprint import pformat
ds = [{'hello': 'there'}]
logging.debug(pformat(ds))
AttributeError: 'function' object has no attribute 'pformat'
any idea why? –
Devoir from pprint import pprint,pformat
then logging.debug((pformat(stuff))
–
Devoir logging.debug("%s", pformat(ds))
you should avoid the overhead of pformat
when the logLevel
is > DEBUG
. Here is a link to good info on string formatting for logging. –
Inconstant logging.debug("%s", pformat(ds))
won't avoid the pformat
call. That format simply means that, if debug logging is disabled, then a new string won't be created by formatting the template string with the other arguments. The arguments themselves, if results of a function call, will be evaluated. –
Stonehenge The solution above didn't quite cut it for me because I'm also using a formatter to add name and levelname when logging. It looks a little untidy:
__main__ : DEBUG : ['aaaaaaaaaaaaaaaaaaaa',
'bbbbbbbbbbbbbbbbbbbb',
'cccccccccccccccccccc',
'dddddddddddddddddddd']
__main__ : DEBUG : Some other logging text
There may be a more elegant solution, but this:
for line in pprint.pformat(ds).split('\n'):
logging.debug(line)
produces something a little nicer:
__main__ : DEBUG : ['aaaaaaaaaaaaaaaaaaaa',
__main__ : DEBUG : 'bbbbbbbbbbbbbbbbbbbb',
__main__ : DEBUG : 'cccccccccccccccccccc',
__main__ : DEBUG : 'dddddddddddddddddddd']
__main__ : DEBUG : Some other logging text
\n
character in the pformat. At least this way the block is together. –
Borges pformat()
and prefixes every line in the output with the configured logger format. –
Evin An alternative is to use json.dumps
with the indent
arg. In some cases (depending on logging format, data size, etc) it might give you nicer output.
logging.error('Malformed input data!')
logging.error(pformat(foo))
ERROR:root:Malformed input data!
ERROR:root:{'a': 1, 'b': 2, 'c': 'womp rat', 'd': 'turd sandwich'}
vs.
logging.error('Malformed input data!')
logging.error(json.dumps(foo, indent=4))
ERROR:root:Malformed input data!
ERROR:root:{
"a": 1,
"b": 2,
"c": "womp rat",
"d": "turd sandwich"
}
\n
. –
Legit © 2022 - 2024 — McMap. All rights reserved.
pprint( {}, stream )
, but found it rather awkward. i would have thought something likespprint
might have been nicer thanpformat
(like inc
). – Lanlanapprint.pformat()
was on that page. – Samhita