Skip to content

Commit 7ef89c3

Browse files
committed
Proper log4j format emulation
log4j writes the XML "manually", see https://github.com/apache/log4j/blob/v1_2_17/src/main/java/org/apache/log4j/xml/XMLLayout.java#L137-L145 The resulting XML is impossible to write with a standard compliant XML writer such as XmlWriter. That's why we write the event in a StringWriter then massage the output to remove the xmlns:log4j attribute to match log4j output. The XML fragment becomes valid when surrounded by an external entity, see https://github.com/apache/log4j/blob/v1_2_17/src/main/java/org/apache/log4j/xml/XMLLayout.java#L31-L49
1 parent ae81378 commit 7ef89c3

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

src/Log4NetTextFormatter.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,22 @@ public void Format(LogEvent logEvent, TextWriter output)
8282
{
8383
throw new ArgumentNullException(nameof(output));
8484
}
85-
using var writer = XmlWriter.Create(output, _options.XmlWriterSettings);
85+
var xmlWriterOutput = UsesLog4JCompatibility ? new StringWriter() : output;
86+
using var writer = XmlWriter.Create(xmlWriterOutput, _options.XmlWriterSettings);
8687
WriteEvent(logEvent, writer);
8788
writer.Flush();
89+
if (UsesLog4JCompatibility)
90+
{
91+
// log4j writes the XML "manually", see https://github.com/apache/log4j/blob/v1_2_17/src/main/java/org/apache/log4j/xml/XMLLayout.java#L137-L145
92+
// The resulting XML is impossible to write with a standard compliant XML writer such as XmlWriter.
93+
// That's why we write the event in a StringWriter then massage the output to remove the xmlns:log4j attribute to match log4j output.
94+
// The XML fragment becomes valid when surrounded by an external entity, see https://github.com/apache/log4j/blob/v1_2_17/src/main/java/org/apache/log4j/xml/XMLLayout.java#L31-L49
95+
const string log4JNamespaceAttribute = @" xmlns:log4j=""http://jakarta.apache.org/log4j/""";
96+
var xmlString = xmlWriterOutput.ToString();
97+
var i = xmlString.IndexOf(log4JNamespaceAttribute, StringComparison.Ordinal);
98+
output.Write(xmlString.Substring(0, i));
99+
output.Write(xmlString.Substring(i + log4JNamespaceAttribute.Length));
100+
}
88101
output.Write(_options.XmlWriterSettings.NewLineChars);
89102
}
90103

tests/Log4NetTextFormatterTest.Log4JCompatibility.approved.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<log4j:event timestamp="1041689366535" level="INFO" xmlns:log4j="http://jakarta.apache.org/log4j/">
1+
<log4j:event timestamp="1041689366535" level="INFO">
22
<log4j:properties>
33
<log4j:data name="π" value="3.14" />
44
</log4j:properties>

0 commit comments

Comments
 (0)