-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #101 from MEHRSHAD-MIRSHEKARY/feat/flat-formatter
✨ feat(formatters): Add FLATFormatter to Format Log Records as Flat Line Key-Value Pairs
- Loading branch information
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |