Skip to content

Commit

Permalink
Escape newlines in LogfmtRenderer (#592)
Browse files Browse the repository at this point in the history
* Escape newlines in LogfmtRenderer

* Update tests/test_processors.py

---------

Co-authored-by: Hynek Schlawack <[email protected]>
  • Loading branch information
madjar and hynek authored Jan 29, 2024
1 parent 5c3bc79 commit b93037f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ You can find our backwards-compatibility policy [here](https://github.com/hynek/

## [Unreleased](https://github.com/hynek/structlog/compare/24.1.0...HEAD)

### Changed

- `structlog.processors.LogfmtRenderer` now escapes newlines.
[#592](https://github.com/hynek/structlog/pull/592)

## [24.1.0](https://github.com/hynek/structlog/compare/23.3.0...24.1.0) - 2024-01-08

Expand Down
2 changes: 1 addition & 1 deletion src/structlog/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ def __call__(
continue
value = "true" if value else "false"

value = f"{value}".replace('"', '\\"')
value = f"{value}".replace('"', '\\"').replace("\n", "\\n")

if " " in value or "=" in value:
value = f'"{value}"'
Expand Down
10 changes: 10 additions & 0 deletions tests/test_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,16 @@ def test_invalid_key(self):
with pytest.raises(ValueError, match='Invalid key: "invalid key"'):
LogfmtRenderer()(None, None, event_dict)

def test_newline_in_value(self):
"""
Newlines in values are escaped.
"""
event_dict = {"with_newline": "some\nvalue"}

rv = LogfmtRenderer()(None, None, event_dict)

assert r"with_newline=some\nvalue" == rv


class TestJSONRenderer:
def test_renders_json(self, event_dict):
Expand Down

0 comments on commit b93037f

Please sign in to comment.