Skip to content

Commit

Permalink
Merge pull request #101 from MEHRSHAD-MIRSHEKARY/feat/flat-formatter
Browse files Browse the repository at this point in the history
✨ feat(formatters): Add FLATFormatter to Format Log Records as Flat Line Key-Value Pairs
  • Loading branch information
ARYAN-NIKNEZHAD authored Oct 4, 2024
2 parents 69b0ecd + bf017c1 commit aa38f42
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions django_logging/formatters/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
from .colored_formatter import ColoredFormatter
from .flat_formatter import FLATFormatter
from .json_formatter import JSONFormatter # pylint: disable=E0401, E0611
from .xml_formatter import XMLFormatter # pylint: disable=E0401, E0611
35 changes: 35 additions & 0 deletions django_logging/formatters/flat_formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from logging import LogRecord

from django_logging.formatters.base import ( # pylint: disable=E0401, E0611
BaseStructuredFormatter,
)


class FLATFormatter(BaseStructuredFormatter):
"""A custom log formatter that formats log records as a single flat line
string, with key-value pairs like `asctime='2019-04-13' level='INFO'`."""

def format(self, record: LogRecord) -> str:
"""Formats the log record as a flat line string.
Args:
----
record (logging.LogRecord): The log record object.
Returns:
-------
str: The formatted flat line string.
"""
# Build the flat line string based on the specifiers
flat_line = " ".join(
f"{specifier}='{self._get_field_value(record, specifier)}'"
for specifier in self.specifiers
if self._get_field_value(record, specifier) is not None
)

# Add exception information if available
if record.exc_info:
flat_line += f" exception='{self.formatException(record.exc_info)}'"

return flat_line

0 comments on commit aa38f42

Please sign in to comment.