From bf017c1e7a73f8b736ea76e67e94f9168419a917 Mon Sep 17 00:00:00 2001 From: MEHRSHAD MIRSHEKARY Date: Fri, 4 Oct 2024 13:06:42 +0330 Subject: [PATCH] :sparkles: feat(formatters): Add FLATFormatter to Format Log Records as Flat Line 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 --- django_logging/formatters/__init__.py | 3 ++ django_logging/formatters/flat_formatter.py | 35 +++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 django_logging/formatters/flat_formatter.py diff --git a/django_logging/formatters/__init__.py b/django_logging/formatters/__init__.py index cd8b46e..fe40a2c 100644 --- a/django_logging/formatters/__init__.py +++ b/django_logging/formatters/__init__.py @@ -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 diff --git a/django_logging/formatters/flat_formatter.py b/django_logging/formatters/flat_formatter.py new file mode 100644 index 0000000..a6698c3 --- /dev/null +++ b/django_logging/formatters/flat_formatter.py @@ -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