Skip to content

Python log formatter according to Google Cloud v2 Specification

License

Notifications You must be signed in to change notification settings

rai200890/python_google_cloud_logger

Repository files navigation

python_google_cloud_logger

CircleCI PyPI version Maintainability Test Coverage

Python log formatter for Google Cloud according to v2 specification using python-json-logger formatter

Inspired by Elixir's logger_json

Instalation

Pipenv

    pipenv install google_cloud_logger 

Pip

    pip install google_cloud_logger 

Usage

LOG_CONFIG = {
    "version": 1,
    "formatters": {
        "json": {
            "()": "google_cloud_logger.GoogleCloudFormatter",
            "application_info": {
                "type": "python-application",
                "name": "Example Application"
            },
            "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s"
        }
    },
    "handlers": {
        "json": {
            "class": "logging.StreamHandler",
            "formatter": "json"
        }
    },
    "loggers": {
        "root": {
            "level": "INFO",
            "handlers": ["json"]
        }
    }
}
import logging

from logging import config

config.dictConfig(LOG_CONFIG) # load log config from dict

logger = logging.getLogger("root") # get root logger instance


logger.info("farofa", extra={"extra": "extra"}) # log message with extra arguments  

Example output:

{"timestamp": "2018-11-03T22:05:03.818000Z", "severity": "INFO", "message": "farofa", "labels": {"type": "python-application", "name": "Example Application"}, "metadata": {"userLabels": {"extra": "extra"}}, "sourceLocation": {"file": "<ipython-input-9-8e9384d78e2a>", "line": 1, "function": "<module>"}}

Credits

Thanks @thulio, @robsonpeixoto, @ramondelemos