python-json-logger
python-json-logger copied to clipboard
Json log formatting in google cloud functions
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.
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).