Home > Back-end >  With JSON logs can I merge multiple values under a single key
With JSON logs can I merge multiple values under a single key

Time:01-07

I want to merge multiple values under a single JSON key while logging it to the console.

Here is a code snippet


import logging
from pythonjsonlogger import jsonlogger


LOG_FORMAT = '%(asctime)s %(levelname)s %(filename)s %(funcName)s %(threadName) %(message)'

logformatter = jsonlogger.JsonFormatter(LOG_FORMAT)
stdloghandler.setFormatter(logformatter)
logger.addHandler(stdloghandler)

Generated Output:

{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "filename": "xyz.py", "funcName": "abc", "threadName": "MainThread", "message": "..............."}

Expected output:

I want to merge filename,funcName,threadName under one key

Something like this

{"asctime": "2022-01-06 12:21:03,878", "levelname": "DEBUG", "file": "xyz.py:abc:MainThread", "message": "..............."}
"file": "xyz.py:abc:MainThread"

I didn't find any examples which did this nor any documents. Reference: https://pypi.org/project/python-json-logger/

CodePudding user response:

The documentation you linked here shows how to create a custom format. You can also see the attributes of the LogRecord that is passed in to the function call.

class CustomJsonFormatter(jsonlogger.JsonFormatter):
    def add_fields(self, log_record, record, message_dict):
        super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)

        custom_msg = f"{record.filename}:{record.funcName}:{record.threadName}"
        log_record["file"] = custom_msg

formatter = CustomJsonFormatter('%(asctime)s %(levelname)s %(file)s %(message)')
  •  Tags:  
  • Related