32 lines
773 B
Python
32 lines
773 B
Python
# Adapted from https://github.com/jkakar/logfmt-python/blob/master/logfmt/formatter.py
|
|
|
|
from typing import Any, Dict
|
|
|
|
CHARS_TO_ESCAPE = [" ", "=", "\\", '"', "'"]
|
|
|
|
|
|
def bool_to_str(i: bool) -> str:
|
|
return str(i).lower()
|
|
|
|
|
|
def escape_value(value: str):
|
|
value = value.replace('"', '\\"')
|
|
if any(char in value for char in CHARS_TO_ESCAPE):
|
|
value = '"{}"'.format(value)
|
|
return value
|
|
|
|
|
|
def logfmt(data: Dict[str, Any]):
|
|
out = []
|
|
for k, v in data.items():
|
|
if not k.isidentifier():
|
|
continue
|
|
if v is None:
|
|
v = ""
|
|
elif isinstance(v, bool):
|
|
v = bool_to_str(v)
|
|
elif isinstance(v, str):
|
|
v = escape_value(v)
|
|
out.append("{}={}".format(k, v))
|
|
return " ".join(out)
|