Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed
- Logging a `dict` no longer modifies it. `exc_info` and `stack_info` were previously added to the caller's `dict`. [#66](https://github.com/nhairs/python-json-logger/pull/66)
- `$` style formats now support unbraced `$name` fields, not just `${name}`. [#18](https://github.com/nhairs/python-json-logger/issues/18)

Thanks @gaoflow

Expand Down
11 changes: 9 additions & 2 deletions src/pythonjsonlogger/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@
RESERVED_ATTRS.sort()


STYLE_STRING_TEMPLATE_REGEX = re.compile(r"\$\{(.+?)\}", re.IGNORECASE) # $ style
STYLE_STRING_TEMPLATE_REGEX = re.compile(
r"\$(?:\$|\{(?P<braced>.+?)\}|(?P<named>[_a-z][_a-z0-9]*))", re.IGNORECASE
) # $ style
STYLE_STRING_FORMAT_REGEX = re.compile(r"\{(.+?)\}", re.IGNORECASE) # { style
STYLE_PERCENT_REGEX = re.compile(r"%\((.+?)\)", re.IGNORECASE) # % style

Expand Down Expand Up @@ -302,7 +304,12 @@ def parse(self) -> list[str]:
raise ValueError(f"Style {self._style!r} is not supported")

if isinstance(self._style, logging.StringTemplateStyle):
formatter_style_pattern = STYLE_STRING_TEMPLATE_REGEX
# String templates support both ${name} and $name, and $$ is an escaped literal
return [
match.group("braced") or match.group("named")
for match in STYLE_STRING_TEMPLATE_REGEX.finditer(self._fmt)
if match.group("braced") or match.group("named")
]

elif isinstance(self._style, logging.StrFormatStyle):
formatter_style_pattern = STYLE_STRING_FORMAT_REGEX
Expand Down
16 changes: 16 additions & 0 deletions tests/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,22 @@ def test_percentage_format(env: LoggingEnvironment, class_: type[BaseJsonFormatt
return


@pytest.mark.parametrize("class_", ALL_FORMATTERS)
def test_string_template_format(env: LoggingEnvironment, class_: type[BaseJsonFormatter]):
# Note: string templates support both $name and ${name}, and $$ is an escaped literal $
env.set_formatter(
class_("$$literal $levelname ${message} $filename ${lineno} $asctime", style="$")
)

msg = "testing logging format"
env.logger.info(msg)
log_json = env.load_json()

assert log_json["message"] == msg
assert log_json.keys() == {"levelname", "message", "filename", "lineno", "asctime"}
return


@pytest.mark.parametrize("class_", ALL_FORMATTERS)
def test_comma_format(env: LoggingEnvironment, class_: type[BaseJsonFormatter]):
# Note: we have double comma `,,` to test handling "empty" names
Expand Down
Loading