0

I want to change the keys' names in my python json logger:

import logging
from pythonjsonlogger import jsonlogger

def main() -> None:

    logger = logging.getLogger("myLovelyLogger")
    logger.warning("something terrible happened")

if __name__ == "__main__":

    logger = logging.getLogger("myLovelyLogger")
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)

    formatter = jsonlogger.JsonFormatter(
        fmt="%(asctime)s %(name)s %(levelname)s %(message)s",
        datefmt="%d/%m/%y[ %H:%M:%S ]",
        json_indent=4
    )

    handler.setFormatter(formatter)
    logger.addHandler(handler)

    main()

When I run it, everything goes well, I just want to change some keys' names:

$ python3 main.py
{
    "asctime": "29/06/22[ 13:44:55 ]", # <--- change "asctime" to "time"
    "name": "myLovelyLogger",
    "levelname": "WARNING",            # <--- change "levelname" to "level"
    "message": "something terrible happened"
}

How can I achieve that?

OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87
  • Does this answer your question? [python logging - With JSON logs can I add an "extra" value to every single log?](https://stackoverflow.com/questions/54471689/python-logging-with-json-logs-can-i-add-an-extra-value-to-every-single-log). There is also [example in the docs](https://github.com/madzak/python-json-logger#customizing-fields). – buran Jun 29 '22 at 10:51
  • @buran the post you mentioned was indeed similar, but still different enough. thanks. – OrenIshShalom Jun 29 '22 at 11:11
  • Thanks for sharing the solution. I'll retract my closing vote – buran Jun 29 '22 at 11:15

1 Answers1

2

Apparently I missed this option in the documentation.

    formatter = jsonlogger.JsonFormatter(
        fmt="%(asctime)s %(name)s %(levelname)s %(message)s",
        rename_fields={"asctime": "time", "levelname": "level"}, # <--- added this line
        datefmt="%d/%m/%y[ %H:%M:%S ]",
        json_indent=4
    )

Then I get the desired result :

$ python3 main.py
{
    "time": "29/06/22[ 14:10:12 ]",
    "name": "myLovelyLogger",
    "level": "WARNING",
    "message": "something terrible happened"
}
OrenIshShalom
  • 5,974
  • 9
  • 37
  • 87