tommikaikkonen / prettyprinter

Syntax-highlighting, declarative and composable pretty printer for Python 3.5+
https://prettyprinter.readthedocs.io
MIT License
336 stars 20 forks source link

Using with logging #1

Closed asyncee closed 6 years ago

asyncee commented 6 years ago

Hi, very nice and beautiful package.

But how do i use it with logging?

For example, if i have a StreamLogger, should i write a custom formatter for it?

tommikaikkonen commented 6 years ago

I'm not very familiar with using pretty printers in a logging context, but here are my thoughts.

prettyprinter.pformat returns output as a string, which you could use for logging. This output will not be syntax highlighted. (You can output cpprint to a StringIO instance using the stream kwarg if you want a string with syntax highlighting.)

Now, if you want to have this kind of statement

logger.info('Value: %s', [1, 2, 3])

to use PrettyPrinter to render args like [1, 2, 3] above, looking at the logging module source, you would have to override LogRecord.getMessage(), so that you first call prettyprinter.pformat on each of the args before the logging module casts the args to strings with msg % args in LogRecord.getMessage. It seems like you could bypass the getMessage() call by writing a custom formatter (see this line), which might be easier.

Note that:

asyncee commented 6 years ago

Great, thank you very much for detailed explanation!