madzak / python-json-logger

Json Formatter for the standard python logger
BSD 2-Clause "Simplified" License
1.7k stars 231 forks source link

Json log formatting in google cloud functions #112

Closed nitishxp closed 1 year ago

nitishxp commented 3 years ago

Hi,

I am using this lib to print the logs in CF but some of the logs are not being printed in Google Cloud logs. Google says to give log output in following format {"severity": <>, "message": <>}

but the lib is also returning some other info in case if log message is dict can you help me to give me the proper code to get only these two keys in the output log.

lukeschlather commented 3 years ago

This is what I arrived at:

import logging
import sys

from pythonjsonlogger import jsonlogger

logger = logging.getLogger()
logger.setLevel(logging.INFO)

logHandler = logging.StreamHandler(sys.stdout)

# e.g. {"message": "<>", "levelname": "INFO", "filename": "<>.py", "asctime": "2021-01-20 11:10:00,447", "funcName": "<>", "lineno": 51}
format_str = '%(message)%(levelname)%(filename)%(asctime)%(funcName)%(lineno)'
formatter = jsonlogger.JsonFormatter(format_str, rename_fields={"levelname": "severity"})
logHandler.setFormatter(formatter)
logger.addHandler(logHandler)

If you want to exclude the other fields you can make the format string just %(message)%(levelname).