Skip to content

Commit

Permalink
✨ feat(formatters): Add FLATFormatter to Format Log Records as Flat L…
Browse files Browse the repository at this point in the history
…ine Key-Value Pairs

#### Key Features:
- Formats log fields as key-value pairs, e.g., �sctime='2024-10-04' level='INFO' message='Log message here'.
- Ignores fields with empty or None values.
- Adds exception information to the log string if present in the log record.
- Inherits specifier extraction and handling from BaseStructuredFormatter.

This formatter is ideal for use cases that require concise, human-readable logs without structured formats such as JSON or XML.

Closes #98
  • Loading branch information
MEHRSHAD-MIRSHEKARY committed Oct 4, 2024
1 parent b76afa1 commit bf017c1
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 bf017c1

Please sign in to comment.