Skip to content

Commit 2eaf5ca

Browse files
committed
Escape newline characters
1 parent d7f10a6 commit 2eaf5ca

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

logfmter/formatter.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,16 @@ def format_string(cls, value: str) -> str:
3838
"""
3939
Process the provided string with any necessary quoting and/or escaping.
4040
"""
41-
needs_escaping = '"' in value
41+
needs_dquote_escaping = '"' in value
42+
needs_newline_escaping = "\n" in value
4243
needs_quoting = " " in value or "=" in value
4344

44-
if needs_escaping:
45+
if needs_dquote_escaping:
4546
value = value.replace('"', '\\"')
4647

48+
if needs_newline_escaping:
49+
value = value.replace("\n", "\\n")
50+
4751
if needs_quoting:
4852
value = '"{}"'.format(value)
4953

tests/test_formatter.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
(' "', '" \\""'),
2020
# If the string is empty, then it should be quoted.
2121
("", '""'),
22+
# If the string contains a newline, then it should be escaped.
23+
("\n", "\\n"),
24+
("\n\n", "\\n\\n"),
2225
],
2326
)
2427
def test_format_string(value, expected):

0 commit comments

Comments
 (0)