Created
November 30, 2021 10:55
-
-
Save branneman/1dc16bef66591296fd77dfa24edd2fbf to your computer and use it in GitHub Desktop.
Python log util, outputting elastic/filebeat compatible json
This file contains hidden or 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
import json | |
from datetime import datetime, timezone | |
LEVELS = { | |
"emergency": 7, | |
"alert": 6, | |
"critical": 5, | |
"error": 4, | |
"warning": 3, | |
"notice": 2, | |
"info": 1, | |
"debug": 0, | |
} | |
# Module state, mutated via logConfigure() | |
type = None | |
minimumLevel = None | |
def logConfigure(logType, level): | |
if level not in LEVELS.keys(): | |
raise Exception("log(): logConfigure called with incorrect level") | |
global minimumLevel, type | |
type = logType | |
minimumLevel = level | |
def log(level, message, userType="ANONYMOUS"): | |
if minimumLevel is None: | |
raise Exception("log(): minimumLevel is None. Was logConfigure() called?") | |
# Don't log if level isn't at least minimumLevel | |
if LEVELS[level] < LEVELS[minimumLevel]: | |
return | |
stmt = { | |
"level": level, | |
"type": type, | |
"message": message, | |
"timestamp": datetimeToIso8601(datetime.now()), | |
"userType": userType, | |
} | |
jsonstr = json.dumps(stmt, separators=(",", ":")) # most compact | |
print("[ELASTIC]" + jsonstr) | |
# ISO 8601: YYYY-MM-DDTHH:mm:ss.sssZ | |
def datetimeToIso8601(local): | |
utc = local.astimezone(timezone.utc) | |
millisec = utc.strftime("%f")[:3] | |
return utc.strftime("%Y-%m-%dT%H:%M:%S." + millisec + "Z") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment