Created
October 24, 2022 16:36
-
-
Save bqbn/66417a894ad0b48c6c8605205de42bbc to your computer and use it in GitHub Desktop.
Test making MozLog compatible with GKE logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from dockerflow.logging import JsonLogFormatter | |
import logging.config | |
import sys | |
try: | |
greet = sys.argv[1] | |
except IndexError: | |
greet = "world" | |
class LittleCaseSeverityJSONFormatter(JsonLogFormatter): | |
"""Use the little case "severity" key per | |
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/master/lib/fluent/plugin/out_google_cloud.rb#L1416-L1424 | |
""" | |
def convert_record(self, record): | |
out = super().convert_record(record) | |
out["severity"] = out["Severity"] | |
return out | |
cfg = { | |
'version': 1, | |
'formatters': { | |
'json': { | |
'()': '__main__.LittleCaseSeverityJSONFormatter', | |
'logger_name': 'myproject' | |
} | |
}, | |
'handlers': { | |
"console": { | |
"level": "DEBUG", | |
"class": "logging.StreamHandler", | |
"formatter": "json", | |
}, | |
}, | |
'loggers': { | |
'myproject': { | |
'handlers': ['console'], | |
'level': 'DEBUG', | |
}, | |
}, | |
} | |
logging.config.dictConfig(cfg) | |
logger = logging.getLogger('myproject') | |
# Map from Python logging to GCP cloud logging | |
# Per https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity | |
logger.handlers[0].formatter.SYSLOG_LEVEL_MAP = { | |
50: 600, # CRITICAL | |
40: 500, # ERROR | |
30: 400, # WARNING | |
20: 200, # INFO | |
10: 100, # DEBUG | |
} | |
logger.debug(f"debug: {__file__}, hello {greet}") | |
logger.info(f"info: {__file__}, hello {greet}") | |
logger.warning(f"warning: {__file__}, hello {greet}") | |
logger.error(f"error: {__file__}, hello {greet}") | |
logger.critical(f"critical: {__file__}, hello {greet}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment