Skip to content

Commit de8377b

Browse files
committed
Escape leading @ in property names, since these can in fact be created through ForContext()
1 parent 32764c9 commit de8377b

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/Serilog.Formatting.Compact/Formatting/Compact/CompactJsonFormatter.cs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,15 @@ public static void FormatEvent(LogEvent logEvent, TextWriter output, JsonValueFo
102102

103103
foreach (var property in logEvent.Properties)
104104
{
105+
var name = property.Key;
106+
if (name.Length > 0 && name[0] == '@')
107+
{
108+
// Escape first '@' by doubling
109+
name = '@' + name;
110+
}
111+
105112
output.Write(',');
106-
JsonValueFormatter.WriteQuotedJsonString(property.Key, output);
113+
JsonValueFormatter.WriteQuotedJsonString(name, output);
107114
output.Write(':');
108115
valueFormatter.Format(property.Value, output);
109116
}

test/Serilog.Formatting.Compact.Tests/CompactJsonFormatterTests.cs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Serilog.Formatting.Compact.Tests
99
{
1010
public class CompactJsonFormatterTests
1111
{
12-
void AssertValidJson(Action<ILogger> act)
12+
JObject AssertValidJson(Action<ILogger> act)
1313
{
1414
var output = new StringWriter();
1515
var formatter = new CompactJsonFormatter();
@@ -22,7 +22,7 @@ void AssertValidJson(Action<ILogger> act)
2222
var json = output.ToString();
2323

2424
// Unfortunately this will not detect all JSON formatting issues; better than nothing however.
25-
JObject.Parse(json);
25+
return JObject.Parse(json);
2626
}
2727

2828
[Fact]
@@ -66,5 +66,17 @@ public void MultipleRenderingsAreDelimited()
6666
{
6767
AssertValidJson(log => log.Information("Rendering {First:x8} and {Second:x8}", 1, 2));
6868
}
69+
70+
[Fact]
71+
public void AtPrefixedPropertyNamesAreEscaped()
72+
{
73+
// Not possible in message templates, but accepted this way
74+
var jobject = AssertValidJson(log => log.ForContext("@Mistake", 42)
75+
.Information("Hello"));
76+
77+
JToken val;
78+
Assert.True(jobject.TryGetValue("@@Mistake", out val));
79+
Assert.Equal(42, val.ToObject<int>());
80+
}
6981
}
7082
}

0 commit comments

Comments
 (0)