Skip to content

Commit dfacf87

Browse files
committed
feat: add logfmt parser
Fixes: #28
1 parent 806f3f4 commit dfacf87

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

src/logfmter/formatter.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import numbers
3+
import shlex
34
import traceback
45
from types import TracebackType
56
from typing import Any, Dict, List, Optional, Tuple, Type, cast
@@ -37,6 +38,30 @@
3738
)
3839

3940

41+
def parse_logfmt(
42+
line: str, aliases: dict[str, str] | None = None, convert_numeric: bool = False
43+
) -> dict[str, str]:
44+
"""
45+
Parse a logfmt formatted string.
46+
"""
47+
aliases = aliases or {}
48+
fields = {}
49+
for token in shlex.split(line):
50+
key, _, value = token.partition("=")
51+
key = aliases.get(key, key)
52+
value = value.replace("\\n", "\n")
53+
if convert_numeric and value.isdigit():
54+
value = int(value)
55+
elif (
56+
convert_numeric
57+
and value.count(".") == 1
58+
and value.replace(".", "").isdigit()
59+
):
60+
value = float(value)
61+
fields[key] = value
62+
return fields
63+
64+
4065
class _DefaultFormatter(logging.Formatter):
4166
def format(self, record):
4267
exc_info = record.exc_info

0 commit comments

Comments
 (0)