python-json-logger icon indicating copy to clipboard operation
python-json-logger copied to clipboard

Json log formatting in google cloud functions

Open nitishxp opened this issue 5 years ago • 1 comments

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.

nitishxp avatar Jan 15 '21 03:01 nitishxp

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).

lukeschlather avatar Jan 29 '21 21:01 lukeschlather