Skip to content

Commit 8be79a9

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

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

src/logfmter/formatter.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import logging
22
import numbers
3+
import shlex
34
import traceback
45
from types import TracebackType
5-
from typing import Any, Dict, List, Optional, Tuple, Type, cast
6+
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
67

78
ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType]
89

@@ -37,6 +38,30 @@
3738
)
3839

3940

41+
def parse_logfmt(
42+
line: str, aliases: Optional[Dict[str, str]] = None, convert_numeric: bool = False
43+
) -> Dict[str, Union[str, int, float]]:
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: Union[str, int, float] = 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)