Python log formatter which shows all kwargs in optional

I hope to add the following log items to my application and display the full extra contents on the console, for example

 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 it possible? According to the official registration documentation, Formatter should be configured with a format string that expects foo and bar , but in my case all I want to do is unload all kwargs extra without prior knowledge of foo and bar .

+5
source share
1 answer

Trying to solve the same problem right now. The problem is that everything that is passed additionally is added as a LogRecord property, and the formatter cannot distinguish it from other LogRecord properties. I just came up with a hacker approach to create a dummy record and compare it with the actual one:

 class ExtraLogFormatter(logging.Formatter): def format(self, record): dummy = logging.LogRecord(None,None,None,None,None,None,None) extra_txt = '' for k,v in record.__dict__.items(): if k not in dummy.__dict__: extra_txt += ', {}={}'.format(k,v) message = super().format(record) return message + extra_txt 
0
source

Source: https://habr.com/ru/post/1257984/


All Articles