From 06cdaf89e43f262eb3ba4c917135164b7d2d5f2a Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 21:28:46 +0100 Subject: [PATCH 1/4] #376 Document that an empty syslog render sends no record - RemoteSyslogAppender, and LocalSyslogAppender with Split - threat model, AGENTS.md, appender pages, one test - ANT-2026-56JOM6HP, ANT-2026-Q4NJFOP3 --- .oss-scanner/threat_model.md | 5 ++++- AGENTS.md | 3 ++- src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs | 6 ++++++ src/log4net/Appender/LocalSyslogAppender.cs | 1 + src/log4net/Appender/RemoteSyslogAppender.cs | 1 + .../manual/configuration/appenders/localsyslogappender.adoc | 5 +++-- .../configuration/appenders/remotesyslogappender.adoc | 3 ++- 7 files changed, 19 insertions(+), 5 deletions(-) diff --git a/.oss-scanner/threat_model.md b/.oss-scanner/threat_model.md index abc41f50..4b7e2c89 100644 --- a/.oss-scanner/threat_model.md +++ b/.oss-scanner/threat_model.md @@ -29,7 +29,8 @@ Matters most: as a format string (`EscapePercent`). - `log4net.Appender.Internal.ContentEscape` and `RemoteSyslogAppender.AppendMessage`: the shared escapes are `\0` for NUL, `\r` and `\n`, and `\uXXXX` for anything else. A sink that cannot carry a - character escapes it visibly; it never drops the character, the rest of the record, or the event. + character escapes it visibly; it never drops the character, the rest of the record, or the event, + except as noted under severity. `AppenderSkeleton.RenderLoggingEvent` escapes lone surrogates for every appender, so a sink needs no call of its own for them. NUL stays per sink. - Anything where untrusted content reaches pattern converters, format expansion, or the appenders @@ -72,6 +73,8 @@ reliability defect or hardening, and say so. That is more useful to us than a se thread, a stack overflow from recursion driven by content). - **Medium**: denial of service from content within normal size limits (unbounded memory, CPU, or a hang of the logging call), or an event or part of a record silently lost because of its content. + Not a finding: `RemoteSyslogAppender` for an empty render, and `LocalSyslogAppender` in `Split` + mode for a render that is empty or only CR and LF, send no record. No text is lost. - **Low**: resource leaks, missing escapes with no demonstrated parser impact, defense in depth. Only claim impact you can demonstrate with the reproducer. diff --git a/AGENTS.md b/AGENTS.md index 939a3c93..188e5060 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -317,7 +317,8 @@ What that leaves for this file is where the answers live in the code: for newlines, and `\uXXXX` for anything else, in `ContentEscape` and in `RemoteSyslogAppender.AppendMessage`. Put new ones in `ContentEscape` rather than in the appender: four appenders have needed the same two so far. Escaping before a length limit, not - after, since an escape is longer than what it replaces. + after, since an escape is longer than what it replaces. Exceptions to the never-drop rule are + noted in `.oss-scanner/threat_model.md`. - **Lone surrogates are the exception to escaping per sink.** `AppenderSkeleton.RenderLoggingEvent` escapes them for every appender and has no opt-out, so a sink adds no call of its own. Only text rendered around it needs one, such as the category of `TraceAppender`. NUL stays per sink. diff --git a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs index 31fc0c39..5906d5a0 100644 --- a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs +++ b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs @@ -239,6 +239,12 @@ public void TabAndNonAsciiTextAreUnchanged() public void SplittingDropsTheEmptyLines() => Assert.That(SplitLines("first\r\nsecond\n\nthird\r"), Is.EqualTo(new[] { "first", "second", "third" })); + /// A render that is empty or only line breaks sends no record, on purpose. + [TestCase("")] + [TestCase("\r\n\n")] + public void SplittingNothingButLineBreaksGivesNoRecord(string message) + => Assert.That(SplitLines(message), Is.Empty); + /// /// The record is the printf format string libc parses, so a percent sign in content would make /// the callee read an argument that was never passed. diff --git a/src/log4net/Appender/LocalSyslogAppender.cs b/src/log4net/Appender/LocalSyslogAppender.cs index cc9f3858..406ac909 100644 --- a/src/log4net/Appender/LocalSyslogAppender.cs +++ b/src/log4net/Appender/LocalSyslogAppender.cs @@ -377,6 +377,7 @@ private string[] GetRecords(string message) { string[] records = NewLineHandling switch { + // Empty lines are dropped on purpose, see .oss-scanner/threat_model.md. SyslogNewLineHandling.Split => Array.ConvertAll(SplitLines(message), line => line.EscapeOtherLineBreaks()), SyslogNewLineHandling.Keep => [message], // Escape, also for undefined values. diff --git a/src/log4net/Appender/RemoteSyslogAppender.cs b/src/log4net/Appender/RemoteSyslogAppender.cs index a4cf2ffd..5e8848aa 100644 --- a/src/log4net/Appender/RemoteSyslogAppender.cs +++ b/src/log4net/Appender/RemoteSyslogAppender.cs @@ -355,6 +355,7 @@ protected override void Append(LoggingEvent loggingEvent) StringBuilder builder = new(); + // An empty render sends no record on purpose, see .oss-scanner/threat_model.md. while (i < message.Length) { // Clear StringBuilder diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/localsyslogappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/localsyslogappender.adoc index 9e06ab59..fc577924 100644 --- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/localsyslogappender.adoc +++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/localsyslogappender.adoc @@ -44,8 +44,9 @@ appender's activation with an error A newline in logged content ends the record for a syslog daemon that writes the message through to a line oriented log, so content can otherwise forge a second, authentic looking entry. `Escape` writes -them as `\r` and `\n`, `Split` sends one record per line, and `Keep` passes them through for a -daemon that handles multiline messages itself. `Escape` and `Split` also write VT, FF, FS, GS, RS, +them as `\r` and `\n`, `Split` sends one record per non-empty line (an empty render or one with +only CR and LF sends none), and `Keep` passes them through for a daemon that handles multiline +messages itself. `Escape` and `Split` also write VT, FF, FS, GS, RS, NEL, U+2028 and U+2029 as `\uXXXX`, since a reader may break a line there; `Keep` passes them through. Note that `syslog(3)` does no escaping of its own: whatever escaping you see on a mainstream Linux comes from the daemon, not from libc. diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/remotesyslogappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/remotesyslogappender.adoc index b5e167db..92dd1159 100644 --- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/remotesyslogappender.adoc +++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/remotesyslogappender.adoc @@ -22,7 +22,8 @@ The `RemoteSyslogAppender` sends log messages to a remote syslog daemon using th It supports configurable syslog facilities and severity levels, but due to the nature of UDP, messages may be lost or truncated. This appender does not include timestamp or hostname fields, as the receiving syslog daemon adds them automatically. -It also splits log messages at line breaks, sending each line as a separate syslog message. +With `newLineHandling` `Split`, it sends each line as a separate syslog message. +An event whose layout renders nothing sends no record. The following example sends all events with Level WARN or higher to the remote server 192.168.1.100 on the default port with UTF8-Encoding. From 49f8bda1088af7a22f3c8ff03d3e44d737a53c84 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 22:19:39 +0100 Subject: [PATCH 2/4] #361 Write a tab in an XML attribute as a character reference on .NET Framework - XmlTextWriter wrote it literally, read back as a space - ANT-2026-8WPIUIID --- .../361-xml-tab-in-attribute-as-reference.xml | 12 ++++++ .../Layout/XmlLayoutSchemaLog4jTest.cs | 30 +++++++++++++++ src/log4net.Tests/Layout/XmlLayoutTest.cs | 38 +++++++++++++++++++ src/log4net.Tests/Layout/XmlRecords.cs | 16 ++++++-- .../Layout/Internal/XmlWriterExtensions.cs | 31 ++++++++++++++- 5 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 src/changelog/3.6.1/361-xml-tab-in-attribute-as-reference.xml diff --git a/src/changelog/3.6.1/361-xml-tab-in-attribute-as-reference.xml b/src/changelog/3.6.1/361-xml-tab-in-attribute-as-reference.xml new file mode 100644 index 00000000..b37ec04f --- /dev/null +++ b/src/changelog/3.6.1/361-xml-tab-in-attribute-as-reference.xml @@ -0,0 +1,12 @@ + + + + + On .NET Framework, `XmlLayout` and `XmlLayoutSchemaLog4J` write a tab in + an attribute, such as a property value or the identity, as `+&#x9;+`, as on .NET Standard + already. A parser read the literal tab back as a space (ANT-2026-8WPIUIID, fixed by + @FreeAndNil) + diff --git a/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs b/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs index ce05f5e9..cd2c68e0 100644 --- a/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs +++ b/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs @@ -142,5 +142,35 @@ public void LineEndsInElementTextReadBackExactly(string element) Assert.That(XmlRecords.RawContent(record, element), Is.EqualTo("a b")); Assert.That(XmlRecords.ElementText(record, element), Is.EqualTo("a\r\nb")); } + + /// + /// A tab in a property name, a property value and the identity reads back as a tab. + /// + [Test] + public void ATabInAnAttributeReadsBackExactly() + { + StringAppender stringAppender = new() { Layout = new XmlLayoutSchemaLog4J() }; + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + BasicConfigurator.Configure(repository, stringAppender); + ILog log = LogManager.GetLogger(repository.Name, "TestLogger"); + LoggingEventData data = new() + { + LoggerName = "TestLogger", + Level = Level.Info, + TimeStampUtc = DateTime.UtcNow, + Message = "message", + Identity = "alice\tadmin", + Properties = new() + }; + data.Properties["alice\tadmin"] = "alice\tadmin"; + + log.Logger.Log(new(null, repository, data)); + + string record = stringAppender.GetString(); + Assert.That(record, Contains.Substring("name=\"alice admin\" value=\"alice admin\"").Using(StringComparison.Ordinal)); + Assert.That(record, Contains.Substring("name=\"log4net:Identity\" value=\"alice admin\"").Using(StringComparison.Ordinal)); + Assert.That(XmlRecords.AttributeValues(record, "name"), Has.Member("alice\tadmin")); + Assert.That(XmlRecords.AttributeValues(record, "value"), Has.Exactly(2).EqualTo("alice\tadmin")); + } } } \ No newline at end of file diff --git a/src/log4net.Tests/Layout/XmlLayoutTest.cs b/src/log4net.Tests/Layout/XmlLayoutTest.cs index 8b068b15..63082325 100644 --- a/src/log4net.Tests/Layout/XmlLayoutTest.cs +++ b/src/log4net.Tests/Layout/XmlLayoutTest.cs @@ -503,6 +503,44 @@ public void ExceptionTextKeepsItsLineEnds() Assert.That(XmlRecords.ElementText(record, "exception"), Is.EqualTo(evt.ExceptionString)); } + /// + /// A tab in an attribute is a character reference, since a parser reads a literal one back as a space. + /// + [TestCase("alice\tadmin", "alice admin", TestName = "TabInTheMiddle")] + [TestCase("\ta\t\tb\t", " a b ", TestName = "LeadingDoubledAndTrailingTabs")] + public void ATabInAPropertyReadsBackExactly(string text, string expected) + { + LoggingEventData evt = CreateBaseEvent(); + evt.Properties![text] = text; + StringAppender stringAppender = new() { Layout = new XmlLayout() }; + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + BasicConfigurator.Configure(repository, stringAppender); + + LogManager.GetLogger(repository.Name, "TestLogger").Logger.Log(new LoggingEvent(evt)); + + string record = stringAppender.GetString(); + Assert.That(record, Is.EqualTo(CreateEventNode(expected, expected))); + Assert.That(XmlRecords.AttributeValues(record, "name"), Is.EqualTo(new[] { text })); + Assert.That(XmlRecords.AttributeValues(record, "value"), Is.EqualTo(new[] { text })); + } + + /// + /// A tab in the identity reads back as a tab. + /// + [Test] + public void ATabInTheIdentityReadsBackExactly() + { + LoggingEventData evt = CreateBaseEvent(); + evt.Identity = "alice\tadmin"; + using StringWriter writer = new(); + + new XmlLayout().Format(writer, new LoggingEvent(evt)); + + string record = writer.ToString(); + Assert.That(record, Contains.Substring(" identity=\"alice admin\" ").Using(StringComparison.Ordinal)); + Assert.That(XmlRecords.AttributeValues(record, "identity"), Is.EqualTo(new[] { "alice\tadmin" })); + } + private string FormatMessage(string message) { LoggingEventData evt = CreateBaseEvent(); diff --git a/src/log4net.Tests/Layout/XmlRecords.cs b/src/log4net.Tests/Layout/XmlRecords.cs index e246184b..d45d2a58 100644 --- a/src/log4net.Tests/Layout/XmlRecords.cs +++ b/src/log4net.Tests/Layout/XmlRecords.cs @@ -35,10 +35,20 @@ internal static class XmlRecords /// /// Parses the records and returns the text of the one element named . /// - /// net462 writes the prefixes undeclared, so a wrapper declares them. internal static string ElementText(string records, string localName) - => XDocument.Parse($"{records}") - .Descendants().Single(element => element.Name.LocalName == localName).Value; + => Parse(records).Descendants().Single(element => element.Name.LocalName == localName).Value; + + /// + /// Parses the records and returns the values of every attribute named . + /// + internal static string[] AttributeValues(string records, string name) + => [.. Parse(records).Descendants().Attributes(name).Select(attribute => attribute.Value)]; + + /// + /// Parses the records inside a wrapper that declares the prefixes, which net462 writes undeclared. + /// + private static XDocument Parse(string records) + => XDocument.Parse($"{records}"); /// /// Returns the content of the one element named as written. diff --git a/src/log4net/Layout/Internal/XmlWriterExtensions.cs b/src/log4net/Layout/Internal/XmlWriterExtensions.cs index 91c46070..b519c59a 100644 --- a/src/log4net/Layout/Internal/XmlWriterExtensions.cs +++ b/src/log4net/Layout/Internal/XmlWriterExtensions.cs @@ -80,6 +80,35 @@ internal static void WriteAttributeStringSafe(this XmlWriter writer, string loca { if (string.IsNullOrEmpty(value)) return; - writer.WriteAttributeString(localName, Transform.MaskXmlInvalidCharacters(value!, mask)); + string masked = Transform.MaskXmlInvalidCharacters(value!, mask); +#if NETSTANDARD2_0_OR_GREATER + writer.WriteAttributeString(localName, masked); +#else + writer.WriteAttributeWithTabReferences(localName, masked); +#endif + } + +#if !NETSTANDARD2_0_OR_GREATER + /// + /// Writes the attribute with each tab as a character reference, since + /// writes it literally and a parser reads that back as a space. + /// + private static void WriteAttributeWithTabReferences(this XmlWriter writer, string localName, string value) + { + if (value.IndexOf('\t') < 0) + { + writer.WriteAttributeString(localName, value); + return; + } + writer.WriteStartAttribute(localName); + string[] parts = value.Split('\t'); + writer.WriteString(parts[0]); + for (int i = 1; i < parts.Length; i++) + { + writer.WriteCharEntity('\t'); + writer.WriteString(parts[i]); + } + writer.WriteEndAttribute(); } +#endif } \ No newline at end of file From 486ea736ecae3cb4e581916404e03a80b19a1404 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 22:26:36 +0100 Subject: [PATCH 3/4] #374 Write a NUL as \0 in TelnetAppender - a telnet client dropped the raw NUL - ANT-2026-O5V9EV3G --- .../3.6.1/374-telnet-nul-escaped.xml | 11 ++++++++ .../Appender/TelnetAppenderTest.cs | 27 ++++++++++++++++--- src/log4net/Appender/TelnetAppender.cs | 9 ++++--- .../appenders/telnetappender.adoc | 2 ++ 4 files changed, 42 insertions(+), 7 deletions(-) create mode 100644 src/changelog/3.6.1/374-telnet-nul-escaped.xml diff --git a/src/changelog/3.6.1/374-telnet-nul-escaped.xml b/src/changelog/3.6.1/374-telnet-nul-escaped.xml new file mode 100644 index 00000000..34a2be84 --- /dev/null +++ b/src/changelog/3.6.1/374-telnet-nul-escaped.xml @@ -0,0 +1,11 @@ + + + + + `TelnetAppender` writes a NUL character as `\0`, as `TraceAppender` and + `LocalSyslogAppender` do. A telnet client dropped the raw NUL, so `adm\0in` showed as `admin` + (ANT-2026-O5V9EV3G, fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Appender/TelnetAppenderTest.cs b/src/log4net.Tests/Appender/TelnetAppenderTest.cs index a1b2471b..5a1ec913 100644 --- a/src/log4net.Tests/Appender/TelnetAppenderTest.cs +++ b/src/log4net.Tests/Appender/TelnetAppenderTest.cs @@ -59,6 +59,26 @@ public sealed class TelnetAppenderTest /// [Test] public void ContentThatCannotBeEncodedDoesNotDisconnectTheClient() + => Assert.That(ReceiveLogged("poison\ud800event"), Does.Contain(@"poison\ud800event")); + + /// + /// A NUL is sent as \0, since a Telnet client drops it. + /// + [Test] + public void ANulIsSentEscaped() + { + string received = ReceiveLogged("adm\0in"); + + Assert.That(received, Does.Contain(@"adm\0in")); + // Ordinal, since Does.Not.Contain finds a NUL that is not there. + Assert.That(received.IndexOf("\0", StringComparison.Ordinal), Is.Negative); + } + + /// + /// Logs and then a marker to a connected client, and returns what it received. + /// + /// The marker only arrives if the client survived the content. + private static string ReceiveLogged(string content) { StringBuilder received = new(); object receivedSyncRoot = new(); @@ -91,10 +111,9 @@ public void ContentThatCannotBeEncodedDoesNotDisconnectTheClient() WaitFor("welcome message", WelcomeMessage); ILogger logger = repository.GetLogger("Telnet"); - logger.Log(typeof(TelnetAppenderTest), Level.Info, "poison\ud800event", null); - // The event after it only arrives if the client survived the one before. + logger.Log(typeof(TelnetAppenderTest), Level.Info, content, null); logger.Log(typeof(TelnetAppenderTest), Level.Info, marker, null); - WaitFor("the event after the unencodable one", marker); + WaitFor("the marker after the content", marker); } } finally @@ -102,7 +121,7 @@ public void ContentThatCannotBeEncodedDoesNotDisconnectTheClient() repository.Shutdown(); } - Assert.That(ReceivedText(), Does.Contain(@"poison\ud800event")); + return ReceivedText(); void Received(string message) { diff --git a/src/log4net/Appender/TelnetAppender.cs b/src/log4net/Appender/TelnetAppender.cs index cb7f9430..f4fcdb13 100644 --- a/src/log4net/Appender/TelnetAppender.cs +++ b/src/log4net/Appender/TelnetAppender.cs @@ -27,6 +27,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using log4net.Appender.Internal; using log4net.Core; using log4net.Util; @@ -52,6 +53,9 @@ namespace log4net.Appender; /// is not encrypted. Keeping untrusted parties away from the port is the operator's /// responsibility, exactly as it is for a log file. /// +/// +/// A NUL character is written as \0, since a Telnet client drops it. +/// /// /// Keith Long /// Nicko Cadell @@ -293,7 +297,7 @@ protected override void Append(LoggingEvent loggingEvent) if (_handler is not null && _handler.HasConnections) { // Queued, not written: a client that stops reading must not hold up the logging thread. - _sender?.TryEnqueue(RenderLoggingEvent(loggingEvent), EnqueueTimeoutMillis); + _sender?.TryEnqueue(RenderLoggingEvent(loggingEvent).EscapeNulCharacters(), EnqueueTimeoutMillis); } } @@ -342,8 +346,7 @@ public SocketClient(Socket socket) _socket = socket; try { - // Belt and braces. Send escapes what cannot be encoded; this keeps a future gap costing - // one character rather than failing the write. + // Belt and braces: an unencodable character becomes U+FFFD instead of failing the write. _writer = new(new NetworkStream(socket), new UTF8Encoding(false)); } catch (Exception e) when (!e.IsFatal()) diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/telnetappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/telnetappender.adoc index c86f3185..615c895e 100644 --- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/telnetappender.adoc +++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/telnetappender.adoc @@ -25,6 +25,8 @@ Unlike every other appender, it does not write to a destination you configure: i connections from clients that reach it. It is intended for diagnostic use on trusted networks; see <>. +A NUL character shows as `\0`, since a telnet client drops it. + At most 20 clients may be connected at the same time; further connection attempts are answered with a message and closed. From 6fbd242d663356d45bf7e001bee44d1336a434a4 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 22:36:37 +0100 Subject: [PATCH 4/4] #375 Let XmlLayoutSchemaLog4J format from a copy of the event's properties - the event no longer gets the four log4j keys - ANT-2026-L9XQVDSD --- ...5-log4j-layout-leaves-event-properties.xml | 13 +++ .../Layout/XmlLayoutSchemaLog4jTest.cs | 83 +++++++++++++++++++ src/log4net/Layout/XmlLayoutSchemaLog4j.cs | 43 ++++------ 3 files changed, 110 insertions(+), 29 deletions(-) create mode 100644 src/changelog/3.6.1/375-log4j-layout-leaves-event-properties.xml diff --git a/src/changelog/3.6.1/375-log4j-layout-leaves-event-properties.xml b/src/changelog/3.6.1/375-log4j-layout-leaves-event-properties.xml new file mode 100644 index 00000000..3dc3df17 --- /dev/null +++ b/src/changelog/3.6.1/375-log4j-layout-leaves-event-properties.xml @@ -0,0 +1,13 @@ + + + + + `XmlLayoutSchemaLog4J` formats from a copy of the event's properties and + no longer adds `log4jmachinename`, `log4japp`, `log4net:Identity` and `log4net:UserName` to the + event. Adding them could break a concurrent flush of a buffering appender. Visible change: appenders + that run after it on the same event no longer see these four keys (ANT-2026-L9XQVDSD, fixed by + @FreeAndNil) + diff --git a/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs b/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs index cd2c68e0..2d5082b0 100644 --- a/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs +++ b/src/log4net.Tests/Layout/XmlLayoutSchemaLog4jTest.cs @@ -18,6 +18,7 @@ #endregion using System; +using System.IO; using log4net.Config; using log4net.Core; using log4net.Layout; @@ -172,5 +173,87 @@ public void ATabInAnAttributeReadsBackExactly() Assert.That(XmlRecords.AttributeValues(record, "name"), Has.Member("alice\tadmin")); Assert.That(XmlRecords.AttributeValues(record, "value"), Has.Exactly(2).EqualTo("alice\tadmin")); } + + /// + /// Formatting leaves the event's properties as they were: the event is shared with other appenders. + /// + [TestCase(true, TestName = "FixedEvent")] + [TestCase(false, TestName = "UnfixedEvent")] + public void FormattingLeavesTheEventsPropertiesAlone(bool isFixed) + { + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + LoggingEvent loggingEvent = isFixed + ? new(null, repository, CreateData()) + : new(typeof(XmlLayoutSchemaLog4JTest), repository, "TestLogger", Level.Info, "message", null); + string[] keys = loggingEvent.GetProperties().GetKeys(); + using StringWriter writer = new(); + + new XmlLayoutSchemaLog4J().Format(writer, loggingEvent); + + Assert.That(loggingEvent.GetProperties().GetKeys(), Is.EquivalentTo(keys)); + Assert.That(loggingEvent.LookupProperty("log4japp"), Is.Null); + } + + /// + /// The translated properties still reach the output. + /// + [Test] + public void TheTranslatedPropertiesAreWritten() + { + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + using StringWriter writer = new(); + + new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, CreateData())); + + string record = writer.ToString(); + Assert.That(record, Does.Contain("name=\"log4jmachinename\" value=\"host\"")); + Assert.That(record, Does.Contain("name=\"log4japp\" value=\"domain\"")); + Assert.That(record, Does.Contain("name=\"log4net:Identity\" value=\"alice\"")); + Assert.That(record, Does.Contain("name=\"log4net:UserName\" value=\"bob\"")); + } + + /// + /// A property the event already has wins over the translated value. + /// + [Test] + public void AnExistingPropertyWins() + { + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + LoggingEventData data = CreateData(); + data.Properties!["log4japp"] = "mine"; + using StringWriter writer = new(); + + new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, data)); + + Assert.That(XmlRecords.AttributeValues(writer.ToString(), "value"), Has.Member("mine").And.No.Member("domain")); + } + + /// + /// An empty identity is not translated. + /// + [Test] + public void AnEmptyValueIsNotTranslated() + { + ILoggerRepository repository = LogManager.CreateRepository(Guid.NewGuid().ToString()); + LoggingEventData data = CreateData(); + data.Identity = ""; + using StringWriter writer = new(); + + new XmlLayoutSchemaLog4J().Format(writer, new(null, repository, data)); + + Assert.That(XmlRecords.AttributeValues(writer.ToString(), "name"), Has.No.Member(LoggingEvent.IdentityProperty)); + } + + private static LoggingEventData CreateData() => new() + { + LoggerName = "TestLogger", + Level = Level.Info, + TimeStampUtc = DateTime.UtcNow, + Message = "message", + Domain = "domain", + Identity = "alice", + UserName = "bob", + Properties = new() { [LoggingEvent.HostNameProperty] = "host" } + }; } } \ No newline at end of file diff --git a/src/log4net/Layout/XmlLayoutSchemaLog4j.cs b/src/log4net/Layout/XmlLayoutSchemaLog4j.cs index c8f1636f..5f3acbe3 100644 --- a/src/log4net/Layout/XmlLayoutSchemaLog4j.cs +++ b/src/log4net/Layout/XmlLayoutSchemaLog4j.cs @@ -126,34 +126,12 @@ at org.apache.log4j.chainsaw.Generator.run(Generator.java:94) /// protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { - // Translate logging events for log4j - - // Translate hostname property - if (loggingEvent.EnsureNotNull().LookupProperty(LoggingEvent.HostNameProperty) is not null - && loggingEvent.LookupProperty("log4jmachinename") is null) - { - loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty); - } - - // translate appdomain name - if (loggingEvent.LookupProperty("log4japp") is null && loggingEvent.Domain?.Length > 0) - { - loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain; - } - - // translate identity name - if (loggingEvent.Identity?.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) is null) - { - loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity; - } - - // translate user name - if (loggingEvent.UserName.Length > 0 && - loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) is null) - { - loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName; - } + // Translate logging events for log4j, on a copy: the event is shared with other appenders. + PropertiesDictionary properties = new(loggingEvent.EnsureNotNull().GetProperties()); + SetIfMissing("log4jmachinename", properties[LoggingEvent.HostNameProperty]); + SetIfMissing("log4japp", loggingEvent.Domain); + SetIfMissing(LoggingEvent.IdentityProperty, loggingEvent.Identity); + SetIfMissing(LoggingEvent.UserNameProperty, loggingEvent.UserName); // Write the start element writer.EnsureNotNull().WriteStartElement("log4j:event", "log4j", "event", "log4net"); @@ -194,7 +172,6 @@ protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) } // Append the properties text - PropertiesDictionary properties = loggingEvent.GetProperties(); if (properties.Count > 0) { writer.WriteStartElement("log4j:properties", "log4j", "properties", "log4net"); @@ -238,5 +215,13 @@ protected override void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) } writer.WriteEndElement(); + + void SetIfMissing(string key, object? value) + { + if (value is not (null or "") && properties[key] is null) + { + properties[key] = value; + } + } } } \ No newline at end of file