osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

ignoring some default fields from SimpleJsonFormatter


https://docs.python.org/3.7/library/logging.html#logging.Logger.debug
https://docs.python.org/3.7/library/logging.html#logging.Formatter.format


Basically your Formatter string doesn't include %(anotherfield1)s in it anywhere, so that gets ignored. To have a variable number of those in there you'd have to make a custom Formatter class where .format(record) looks for any "left over" keys in the given LogRecord's args, and adds them to the returned message as appropriate.

(Also note that you want 03d for msecs, not 06d)


import logging
import sys
fmt = '{"timestamp": "%(asctime)s.%(msecs)03d", "level":"%(levelname)s"' \
      ', "anottherfield1":"%(anotherfield1)s"}'
datefmt = "%Y-%m-%dT%H:%M:%S"
logging.basicConfig(stream = sys.stdout,
                    level = logging.DEBUG,
                    format = fmt,
                    datefmt = datefmt)
logging.info("my test message", extra = {"anotherfield1": "test"})


{"timestamp": "2018-08-21T12:20:35.475", "level":"INFO", "anottherfield1":"test"}




-----Original Message-----
From: Python-list [mailto:python-list-bounces+david.raymond=tomtom.com at python.org] On Behalf Of shradhattx at gmail.com
Sent: Tuesday, August 21, 2018 11:37 AM
To: python-list at python.org
Subject: ignoring some default fields from SimpleJsonFormatter

I am using for my logger

handler.setFormatter(SimpleJsonFormatter(json.dumps))

It had some default fields - timestamp, function, line_number, module, level

and flexibility to provide extra fields in json log with use of 

   logger.info("my test message", extra={"anotherfield1": "test"})

I am using decorator functions so some of the default fields provided ex- function, line_number, module are not useful as it gives information on decorator module, line_number. 
I like to remove some fields from being logged while retaining others, keeping also the use of "extra"

This is what I tried -
     logging.Formatter('{"timestamp": "%(asctime)s.%(msecs)06d", "level":"%(levelname)s"}',
                        '%Y-%m-%dT%H:%M:%S')

The problem is that it doesn't print the fields given in 'extra'


How do I accomplish this?
-- 
https://mail.python.org/mailman/listinfo/python-list