Skip to content

Commit 3412491

Browse files
spaceonejosheppinette
authored andcommitted
fix: replace invisible control characters in keys with "_"
Fixes: #54
1 parent 7b71554 commit 3412491

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

src/logfmter/formatter.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@
4040
)
4141
REPLACEMENTS = {chr(c): f"\\u{c:04x}" for c in list(range(0x20)) + [0x7F]}
4242
REPLACEMENTS.update({"\n": "\\n", "\t": "\\t", "\r": "\\r"})
43+
KEY_REPLACEMENTS = str.maketrans(
44+
{chr(c): "_" for c in list(range(0x21)) + [0x7F]} | {"\n": "\\n"}
45+
)
4346

4447

4548
class _DefaultFormatter(logging.Formatter):
@@ -124,7 +127,7 @@ def normalize_key(cls, key: str) -> str:
124127
if not key:
125128
return "_"
126129

127-
return key.replace(" ", "_").replace("\n", "\\n")
130+
return key.translate(KEY_REPLACEMENTS)
128131

129132
@classmethod
130133
def get_extra(cls, record: logging.LogRecord) -> dict:

tests/test_formatter.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,10 @@ def test_format_params(value, expected):
111111
("first name", "first_name"),
112112
("", "_"),
113113
("first\nname", "first\\nname"),
114+
(
115+
"".join(map(chr, range(128))),
116+
"__________\\n______________________!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~_",
117+
),
114118
],
115119
)
116120
def test_normalize_key(value, expected):

0 commit comments

Comments
 (0)