Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python log formatter that shows all kwargs in extra

Tags:

python

logging

I hope to add the following log points to my application and display the full contents of extra on console, e.g.,

logger.info('Status', extra={'foo':data})
logger.info('Status', extra={'bar':data})
logger.info('Status', extra={'foo':data, 'bar':data}) 

and I hope to see:

2016-10-10 15:28:31,408, INFO, Status, foo=data
2016-10-10 15:38:31,408, INFO, Status, bar=data
2016-10-10 15:48:31,408, INFO, Status, foo=data, bar=data

Is this even possible? According to official logging documentation, the Formatter must be set up with a format string that expects foo and bar but in my case all I want is to dump out the entire kwargs of extra without prior knowledge of foo and bar.

like image 490
CJLam Avatar asked Oct 10 '16 19:10

CJLam


People also ask

What is Qualname in python logging?

The qualname entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger.

What is Python logging StreamHandler?

StreamHandler. The StreamHandler class, located in the core logging package, sends logging output to streams such as sys. stdout, sys. stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods).

How do I create a multiple logging level in Python?

You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest". In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. So the file has DEBUG entries and the stream outputs only INFO.


1 Answers

Entries of the object passed as extra will become member variables of the LogRecord.

logger.info('Status', extra={'my_params':{'foo':3, 'bar':4}})

Then you can format it as:

handler.setFormatter(logging.Formatter('%(message)s %(my_params)s'))

Which will result in the following log:

#> Status {'foo':3, 'bar':4}}

This assumes you have control over the 'extra' parameter at the time of logging.

like image 169
Voy Avatar answered Nov 07 '22 12:11

Voy