From 37d246a6769bc31c4054b93b5720e7c097cf644a Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 18:17:39 +0100 Subject: [PATCH 1/6] #370 Report the close summary of a background sender once per count - Dispose after Close no longer repeats it, a grown total is reported again - RecordingSink replaces the shared recordings in BackgroundSenderTest - AGENTS.md allows one fixture instance per test --- AGENTS.md | 4 +- .../3.6.1/370-close-summary-once.xml | 11 ++ .../Util/BackgroundSenderTest.cs | 149 ++++++++++-------- .../Util/Internal/RecordingSink.cs | 74 +++++++++ src/log4net/Util/BackgroundSender.cs | 6 +- 5 files changed, 177 insertions(+), 67 deletions(-) create mode 100644 src/changelog/3.6.1/370-close-summary-once.xml create mode 100644 src/log4net.Tests/Util/Internal/RecordingSink.cs diff --git a/AGENTS.md b/AGENTS.md index 4964acbfa..d2f2f2889 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,7 +154,9 @@ almost always be doing. an expanded `params` argument trips CS8620 in a C# 14 extension block, which `WarningsAsErrors=nullable` makes a build error. - **NUnit constructs one fixture instance for the whole fixture**, so an instance field that - records what a test observed accumulates across the tests in it. Clear such state in `[SetUp]`. + records what a test observed accumulates across the tests in it. Clear such state in `[SetUp]`, + or give the fixture `[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]`, as + `BackgroundSenderTest` does. - Drive a test over a background thread with gates (`ManualResetEventSlim`), never with `Thread.Sleep`: park the worker, assert the state you care about, then release it. See `BackgroundSenderTest`, where every wait has a generous timeout and the assertions are exact. diff --git a/src/changelog/3.6.1/370-close-summary-once.xml b/src/changelog/3.6.1/370-close-summary-once.xml new file mode 100644 index 000000000..7bfd6a4e7 --- /dev/null +++ b/src/changelog/3.6.1/370-close-summary-once.xml @@ -0,0 +1,11 @@ + + + + + Closing `TelnetAppender`, `RemoteSyslogAppender` or the `SmtpAppender` of + `log4net.Ext.Mail` reports the total number of messages not sent once, instead of twice + (fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Util/BackgroundSenderTest.cs b/src/log4net.Tests/Util/BackgroundSenderTest.cs index a4280f32d..0d9e41bdf 100644 --- a/src/log4net.Tests/Util/BackgroundSenderTest.cs +++ b/src/log4net.Tests/Util/BackgroundSenderTest.cs @@ -23,6 +23,7 @@ using System.Linq; using System.Threading; +using log4net.Tests.Util.Internal; using log4net.Util; using NUnit.Framework; @@ -33,61 +34,16 @@ namespace log4net.Tests.Util; /// Tests for . /// [TestFixture] +[FixtureLifeCycle(LifeCycle.InstancePerTestCase)] public class BackgroundSenderTest { /// How long a test waits for the background thread before calling it a failure. private const int WaitMillis = 30_000; - private readonly List _sent = []; - private readonly List _reported = []; - - /// - /// NUnit reuses one fixture instance for every test in it, so the recordings have to be - /// cleared between them. - /// - [SetUp] - public void ClearRecordings() - { - lock (_sent) - { - _sent.Clear(); - } - - lock (_reported) - { - _reported.Clear(); - } - } - - private int[] Sent - { - get - { - lock (_sent) - { - return [.. _sent]; - } - } - } - - private void Record(int item) - { - lock (_sent) - { - _sent.Add(item); - } - } - - private void Report(string message, Exception? exception) - { - lock (_reported) - { - _reported.Add(message); - } - } + private readonly RecordingSink _sink = new(); private BackgroundSender CreateSender(int capacity, Action send) - => new("test", capacity, send, Report); + => new("test", capacity, send, _sink.Report); /// /// A queue without room for at least one item cannot work. @@ -105,7 +61,7 @@ public void ConstructorRejectsCapacityBelowOne(int capacity) public void ItemsAreSentInTheOrderTheyWereQueued() { const int itemCount = 100; - using BackgroundSender sender = CreateSender(itemCount, (item, _) => Record(item)); + using BackgroundSender sender = CreateSender(itemCount, (item, _) => _sink.Send(item)); for (int i = 0; i < itemCount; i++) { @@ -113,7 +69,7 @@ public void ItemsAreSentInTheOrderTheyWereQueued() } Assert.That(sender.Flush(WaitMillis), Is.True); - Assert.That(Sent, Is.EqualTo(Enumerable.Range(0, itemCount).ToArray())); + Assert.That(_sink.SentItems, Is.EqualTo(Enumerable.Range(0, itemCount).ToArray())); Assert.That(sender.DroppedItemCount, Is.EqualTo(0)); } @@ -131,7 +87,7 @@ public void AFullQueueDropsInsteadOfBlockingTheCaller() { sendEntered.Set(); release.Wait(WaitMillis); - Record(item); + _sink.Send(item); }); // Park the only sending thread, so that nothing leaves the queue from here on. @@ -151,7 +107,7 @@ public void AFullQueueDropsInsteadOfBlockingTheCaller() release.Set(); Assert.That(sender.Flush(WaitMillis), Is.True); - Assert.That(Sent, Is.EqualTo(new[] { 1, 2, 3 })); + Assert.That(_sink.SentItems, Is.EqualTo(new[] { 1, 2, 3 })); } /// @@ -161,7 +117,7 @@ public void AFullQueueDropsInsteadOfBlockingTheCaller() public void CloseSendsWhatIsStillQueued() { const int itemCount = 10; - BackgroundSender sender = CreateSender(itemCount, (item, _) => Record(item)); + BackgroundSender sender = CreateSender(itemCount, (item, _) => _sink.Send(item)); try { for (int i = 0; i < itemCount; i++) @@ -170,7 +126,7 @@ public void CloseSendsWhatIsStillQueued() } sender.Close(WaitMillis); - Assert.That(Sent, Has.Length.EqualTo(itemCount)); + Assert.That(_sink.SentItems, Has.Length.EqualTo(itemCount)); Assert.That(sender.DroppedItemCount, Is.EqualTo(0)); } finally @@ -193,7 +149,7 @@ public void CloseGivesUpOnAnUnresponsiveSink() sendEntered.Set(); // Answers only when Close runs out of patience and cancels. token.WaitHandle.WaitOne(WaitMillis); - Record(item); + _sink.Send(item); }); try { @@ -208,7 +164,7 @@ public void CloseGivesUpOnAnUnresponsiveSink() Assert.That(stopwatch.ElapsedMilliseconds, Is.LessThan(WaitMillis)); Assert.That(sender.DroppedItemCount, Is.EqualTo(2)); - Assert.That(_reported, Is.Not.Empty); + Assert.That(_sink.Reports, Is.Not.Empty); } finally { @@ -222,7 +178,7 @@ public void CloseGivesUpOnAnUnresponsiveSink() [Test] public void NothingIsAcceptedAfterClose() { - BackgroundSender sender = CreateSender(5, (item, _) => Record(item)); + BackgroundSender sender = CreateSender(5, (item, _) => _sink.Send(item)); try { sender.Close(WaitMillis); @@ -230,7 +186,7 @@ public void NothingIsAcceptedAfterClose() Assert.That(sender.IsFaulted, Is.True); Assert.That(sender.TryEnqueue(1, WaitMillis), Is.False); Assert.That(sender.Flush(WaitMillis), Is.False); - Assert.That(Sent, Is.Empty); + Assert.That(_sink.SentItems, Is.Empty); } finally { @@ -251,7 +207,7 @@ public void AFailedSendDoesNotStopTheOnesAfterIt() throw new InvalidOperationException("simulated send failure"); } - Record(item); + _sink.Send(item); }); for (int i = 0; i < 4; i++) @@ -260,12 +216,12 @@ public void AFailedSendDoesNotStopTheOnesAfterIt() } Assert.That(sender.Flush(WaitMillis), Is.True); - Assert.That(Sent, Is.EqualTo(new[] { 0, 2, 3 })); + Assert.That(_sink.SentItems, Is.EqualTo(new[] { 0, 2, 3 })); Assert.That(sender.DroppedItemCount, Is.EqualTo(1)); // A failed send is not queue pressure and must not be reported as such. - Assert.That(_reported, Has.Some.Contains("Failed to send")); - Assert.That(_reported, Has.None.Contains("queue is full")); + Assert.That(_sink.Reports, Has.Some.Contains("Failed to send")); + Assert.That(_sink.Reports, Has.None.Contains("queue is full")); } /// @@ -289,7 +245,7 @@ public void AnErrorHandlerThatThrowsDoesNotStopTheSender() throw new InvalidOperationException("simulated send failure"); } - Record(item); + _sink.Send(item); }, (_, _) => throw new InvalidOperationException("simulated error handler failure")); @@ -302,7 +258,72 @@ public void AnErrorHandlerThatThrowsDoesNotStopTheSender() Assert.That(sender.IsFaulted, Is.False); }); - Assert.That(Sent, Is.EqualTo(new[] { 0, 2, 3 })); + Assert.That(_sink.SentItems, Is.EqualTo(new[] { 0, 2, 3 })); Assert.That(internalMessages, Is.Not.Empty); } + + /// + /// closes again, which must not repeat the summary. + /// + [Test] + public void CloseThenDisposeReportsTheSummaryOnce() + { + BackgroundSender sender = CreateSender(5, (_, _) => throw new InvalidOperationException("simulated send failure")); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.True); + + sender.Close(WaitMillis); + sender.Dispose(); + + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + } + + /// + /// Disposing without closing first reports the summary too. + /// + [Test] + public void DisposeAloneReportsTheSummaryOnce() + { + BackgroundSender sender = CreateSender(5, (_, _) => throw new InvalidOperationException("simulated send failure")); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.True); + Assert.That(sender.Flush(WaitMillis), Is.True); + + sender.Dispose(); + + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + } + + /// + /// A close with nothing dropped reports nothing, and a drop after it is still reported. + /// + [Test] + public void ACloseWithoutLossesLeavesTheSummaryForLater() + { + BackgroundSender sender = CreateSender(5, (item, _) => _sink.Send(item)); + + sender.Close(WaitMillis); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.False); + sender.Dispose(); + + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + } + + /// + /// A count that grew after the first summary is reported again. + /// + [Test] + public void ACountThatGrewIsReportedAgain() + { + BackgroundSender sender = CreateSender(5, (_, _) => throw new InvalidOperationException("simulated send failure")); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.True); + + sender.Close(WaitMillis); + Assert.That(sender.TryEnqueue(2, WaitMillis), Is.False); + sender.Dispose(); + + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] + { + "[test] 1 logging event(s) in total were not sent.", + "[test] 2 logging event(s) in total were not sent." + })); + } } diff --git a/src/log4net.Tests/Util/Internal/RecordingSink.cs b/src/log4net.Tests/Util/Internal/RecordingSink.cs new file mode 100644 index 000000000..f4b944c60 --- /dev/null +++ b/src/log4net.Tests/Util/Internal/RecordingSink.cs @@ -0,0 +1,74 @@ +#region Apache License +// +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to you under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; + +namespace log4net.Tests.Util.Internal; + +/// +/// Stands in for the send and report callbacks of a and records what each receives. +/// +internal sealed class RecordingSink +{ + private readonly List _sentItems = []; + private readonly List _reports = []; + + internal int[] SentItems + { + get + { + lock (_sentItems) + { + return [.. _sentItems]; + } + } + } + + internal List Reports + { + get + { + lock (_reports) + { + return [.. _reports]; + } + } + } + + internal List CloseSummaries + => [.. Reports.Where(message => message.EndsWith("were not sent.", StringComparison.Ordinal))]; + + internal void Send(int item) + { + lock (_sentItems) + { + _sentItems.Add(item); + } + } + + internal void Report(string message, Exception? exception) + { + lock (_reports) + { + _reports.Add(message); + } + } +} diff --git a/src/log4net/Util/BackgroundSender.cs b/src/log4net/Util/BackgroundSender.cs index 81e374467..eeb6512b5 100644 --- a/src/log4net/Util/BackgroundSender.cs +++ b/src/log4net/Util/BackgroundSender.cs @@ -57,6 +57,7 @@ public sealed class BackgroundSender : IDisposable private readonly CancellationTokenSource _shutdown = new(); private int _droppedItemCount; private int _dropReported; + private int _reportedDropCount; private int _faultReported; private volatile bool _isFaulted; @@ -179,6 +180,7 @@ public bool Flush(int millisecondsTimeout) /// /// Never throws. Once the time is up the send in flight is cancelled and the remaining items /// are counted as dropped, so closing an appender cannot hang on an unresponsive sink. + /// The number dropped is reported once, and again only when it grew. /// /// public void Close(int millisecondsTimeout) @@ -199,9 +201,9 @@ public void Close(int millisecondsTimeout) } int dropped = DroppedItemCount; - if (dropped > 0) + if (dropped > Interlocked.Exchange(ref _reportedDropCount, dropped)) { - Report($"[{_name}] {dropped} logging event(s) were not sent.", null); + Report($"[{_name}] {dropped} logging event(s) in total were not sent.", null); } } From ed950ef8960e863e74fc4a60e27031822d5ff970 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 18:59:54 +0100 Subject: [PATCH 2/6] #370 Let a full send queue wait once until a send succeeds - ANT-2026-M13HDM0A - shared partial for the background sending of the three appenders - sender reports name a message instead of a logging event --- .../3.6.1/370-full-queue-waits-once.xml | 12 +++ .../Appender/SmtpAppenderTest.cs | 4 +- src/log4net.Ext.Mail/Appender/SmtpAppender.cs | 3 + .../Appender/TelnetAppenderTest.cs | 2 +- .../Util/BackgroundSenderTest.cs | 80 +++++++++++++++++-- src/log4net/Appender/RemoteSyslogAppender.cs | 3 + src/log4net/Appender/TelnetAppender.cs | 5 +- src/log4net/Util/BackgroundSender.cs | 18 +++-- .../appenders/remotesyslogappender.adoc | 18 ++--- .../configuration/appenders/smtpappender.adoc | 13 +-- .../appenders/telnetappender.adoc | 10 ++- .../ROOT/partials/background-sender.adoc | 24 ++++++ 12 files changed, 158 insertions(+), 34 deletions(-) create mode 100644 src/changelog/3.6.1/370-full-queue-waits-once.xml create mode 100644 src/site/antora/modules/ROOT/partials/background-sender.adoc diff --git a/src/changelog/3.6.1/370-full-queue-waits-once.xml b/src/changelog/3.6.1/370-full-queue-waits-once.xml new file mode 100644 index 000000000..42027e9af --- /dev/null +++ b/src/changelog/3.6.1/370-full-queue-waits-once.xml @@ -0,0 +1,12 @@ + + + + + When the send queue of `TelnetAppender`, `RemoteSyslogAppender` or the + `SmtpAppender` of `log4net.Ext.Mail` is full, a logging call waits `EnqueueTimeoutMillis` once; later + calls drop at once until a send succeeds, instead of each waiting the full timeout + (ANT-2026-M13HDM0A, fixed by @FreeAndNil) + diff --git a/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs b/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs index 1bf464aa4..5f0fa0b5a 100644 --- a/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs +++ b/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs @@ -523,7 +523,7 @@ public void SendFailureIsReportedToTheErrorHandlerAndNotThrown() Assert.DoesNotThrow(() => Append(appender)); - Assert.That(_errorHandler.Message, Does.Contain("Failed to send a logging event.")); + Assert.That(_errorHandler.Message, Does.Contain("Failed to send a message.")); Assert.That(_errorHandler.Message, Does.Contain("relay refused")); } @@ -869,7 +869,7 @@ public void TheDeadlineStopsASendThatDoesNotFinish() Append(appender); Assert.That(_transport.SentMails, Is.Empty); - Assert.That(_errorHandler.Message, Does.Contain("Failed to send a logging event.")); + Assert.That(_errorHandler.Message, Does.Contain("Failed to send a message.")); Assert.That(_transport.CancelledCalls, Is.EqualTo(new[] { "Send" })); } diff --git a/src/log4net.Ext.Mail/Appender/SmtpAppender.cs b/src/log4net.Ext.Mail/Appender/SmtpAppender.cs index b10f5bf6a..b4916779e 100644 --- a/src/log4net.Ext.Mail/Appender/SmtpAppender.cs +++ b/src/log4net.Ext.Mail/Appender/SmtpAppender.cs @@ -449,6 +449,9 @@ public int SendQueueSize /// /// How long a logging call waits for room in a full queue. Defaults to 5000, 0 never waits. /// + /// + /// Once a wait timed out, logging calls drop without waiting until a send succeeds. + /// /// The value specified is negative. public int EnqueueTimeoutMillis { diff --git a/src/log4net.Tests/Appender/TelnetAppenderTest.cs b/src/log4net.Tests/Appender/TelnetAppenderTest.cs index 4d4dc8a4f..a1b2471b8 100644 --- a/src/log4net.Tests/Appender/TelnetAppenderTest.cs +++ b/src/log4net.Tests/Appender/TelnetAppenderTest.cs @@ -265,7 +265,7 @@ public void EveryInterfaceCanBeAskedFor(string address) /// /// Clients are written to from a background thread, so the queue has to be bounded and the wait - /// for room short: it is the only delay a connected client can impose on the application. + /// for room short: a full queue costs one such wait until a send succeeds. /// [Test] public void SendQueueDefaults() diff --git a/src/log4net.Tests/Util/BackgroundSenderTest.cs b/src/log4net.Tests/Util/BackgroundSenderTest.cs index 0d9e41bdf..24b0de05b 100644 --- a/src/log4net.Tests/Util/BackgroundSenderTest.cs +++ b/src/log4net.Tests/Util/BackgroundSenderTest.cs @@ -274,7 +274,7 @@ public void CloseThenDisposeReportsTheSummaryOnce() sender.Close(WaitMillis); sender.Dispose(); - Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 message(s) in total were not sent." })); } /// @@ -289,7 +289,7 @@ public void DisposeAloneReportsTheSummaryOnce() sender.Dispose(); - Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 message(s) in total were not sent." })); } /// @@ -304,7 +304,7 @@ public void ACloseWithoutLossesLeavesTheSummaryForLater() Assert.That(sender.TryEnqueue(1, WaitMillis), Is.False); sender.Dispose(); - Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 logging event(s) in total were not sent." })); + Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { "[test] 1 message(s) in total were not sent." })); } /// @@ -322,8 +322,78 @@ public void ACountThatGrewIsReportedAgain() Assert.That(_sink.CloseSummaries, Is.EqualTo(new[] { - "[test] 1 logging event(s) in total were not sent.", - "[test] 2 logging event(s) in total were not sent." + "[test] 1 message(s) in total were not sent.", + "[test] 2 message(s) in total were not sent." })); } + + /// + /// After one timed out wait a full queue drops at once, until a send succeeds. + /// + [Test] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2016:Forward the CancellationToken parameter to methods that take one", + Justification = "Stands for a sink that does not cooperate with cancellation.")] + public void AFullQueueWaitsOnceUntilASendSucceeds() + { + using ManualResetEventSlim sendEntered = new(false); + using ManualResetEventSlim release = new(false); + using BackgroundSender sender = CreateSender(1, (item, _) => + { + sendEntered.Set(); + release.Wait(WaitMillis); + _sink.Send(item); + }); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.True); + Assert.That(sendEntered.Wait(WaitMillis), Is.True); + Assert.That(sender.TryEnqueue(2, WaitMillis), Is.True); + + Assert.That(sender.TryEnqueue(3, 1), Is.False); + bool isCongestedAfterTheFirstTimeout = sender.GetFieldValue("_isCongested"); + Stopwatch stopwatch = Stopwatch.StartNew(); + for (int i = 4; i < 14; i++) + { + Assert.That(sender.TryEnqueue(i, 1_000), Is.False); + } + + stopwatch.Stop(); + bool isCongestedAfterTenMore = sender.GetFieldValue("_isCongested"); + release.Set(); + Assert.That(sender.Flush(WaitMillis), Is.True); + + Assert.That(isCongestedAfterTheFirstTimeout, Is.True); + Assert.That(isCongestedAfterTenMore, Is.True); + // Ten waits of a second each without the flag. + Assert.That(stopwatch.ElapsedMilliseconds, Is.LessThan(5_000)); + Assert.That(sender.DroppedItemCount, Is.EqualTo(11)); + Assert.That(sender.GetFieldValue("_isCongested"), Is.False); + Assert.That(_sink.SentItems, Is.EqualTo(new[] { 1, 2 })); + } + + /// + /// A send that throws is no sign the sink drains again, so a full queue still drops at once. + /// + [Test] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2016:Forward the CancellationToken parameter to methods that take one", + Justification = "Stands for a sink that does not cooperate with cancellation.")] + public void AFailedSendKeepsTheQueueCongested() + { + using ManualResetEventSlim sendEntered = new(false); + using ManualResetEventSlim release = new(false); + using BackgroundSender sender = CreateSender(1, (_, _) => + { + sendEntered.Set(); + release.Wait(WaitMillis); + throw new InvalidOperationException("simulated send failure"); + }); + Assert.That(sender.TryEnqueue(1, WaitMillis), Is.True); + Assert.That(sendEntered.Wait(WaitMillis), Is.True); + Assert.That(sender.TryEnqueue(2, WaitMillis), Is.True); + Assert.That(sender.TryEnqueue(3, 1), Is.False); + + release.Set(); + Assert.That(sender.Flush(WaitMillis), Is.True); + + Assert.That(sender.GetFieldValue("_isCongested"), Is.True); + Assert.That(sender.DroppedItemCount, Is.EqualTo(3)); + } } diff --git a/src/log4net/Appender/RemoteSyslogAppender.cs b/src/log4net/Appender/RemoteSyslogAppender.cs index 128b91277..bc1aa14b6 100644 --- a/src/log4net/Appender/RemoteSyslogAppender.cs +++ b/src/log4net/Appender/RemoteSyslogAppender.cs @@ -553,6 +553,9 @@ public int SendQueueSize /// /// How long a logging call waits for room in a full queue. Defaults to 5000, 0 never waits. /// + /// + /// Once a wait timed out, logging calls drop without waiting until a send succeeds. + /// /// The value specified is negative. public int EnqueueTimeoutMillis { diff --git a/src/log4net/Appender/TelnetAppender.cs b/src/log4net/Appender/TelnetAppender.cs index 3df6c4856..9ae2bfd41 100644 --- a/src/log4net/Appender/TelnetAppender.cs +++ b/src/log4net/Appender/TelnetAppender.cs @@ -99,8 +99,9 @@ public int SendQueueSize /// A number of milliseconds, or 0 to drop immediately. The default is 50. /// /// - /// This is the only delay a connected client can impose on the application. While the queue - /// stays full it caps logging at 20 events per second; 0 drops immediately instead of waiting. + /// This is the only delay a connected client can impose on the application. Once a wait + /// timed out, logging calls drop without waiting until a send succeeds; 0 drops immediately + /// instead of waiting. /// /// /// The value specified is negative. diff --git a/src/log4net/Util/BackgroundSender.cs b/src/log4net/Util/BackgroundSender.cs index eeb6512b5..5b524a973 100644 --- a/src/log4net/Util/BackgroundSender.cs +++ b/src/log4net/Util/BackgroundSender.cs @@ -34,7 +34,8 @@ namespace log4net.Util; /// /// An appender that sends over the network blocks the thread that made the logging call, /// and every other thread logging to the same appender behind it, for as long as the sink -/// takes to answer. Queueing the work instead bounds that wait to the enqueue timeout. +/// takes to answer. Queueing the work instead bounds that wait to the enqueue timeout, and once +/// a wait timed out, further items are dropped without waiting until a send succeeds. /// /// /// The queue has a fixed capacity. Work is delivered in the order it was queued, by one @@ -60,6 +61,7 @@ public sealed class BackgroundSender : IDisposable private int _reportedDropCount; private int _faultReported; private volatile bool _isFaulted; + private volatile bool _isCongested; /// /// Creates a queue and starts its background thread. @@ -109,7 +111,8 @@ public BackgroundSender(string name, int capacity, Action /// The item to deliver. /// /// How long to wait for room in a full queue. Zero returns immediately, which loses the item - /// rather than delaying the logging call. + /// rather than delaying the logging call. After a wait timed out, zero is used until a send + /// succeeds. /// /// if the item was queued, if it was dropped. public bool TryEnqueue(T item, int millisecondsTimeout) @@ -118,10 +121,12 @@ public bool TryEnqueue(T item, int millisecondsTimeout) { try { - if (_queue.TryAdd(new Item(item), millisecondsTimeout)) + if (_queue.TryAdd(new Item(item), _isCongested ? 0 : millisecondsTimeout)) { return true; } + + _isCongested = true; } catch (Exception e) when (!e.IsFatal()) { @@ -203,7 +208,7 @@ public void Close(int millisecondsTimeout) int dropped = DroppedItemCount; if (dropped > Interlocked.Exchange(ref _reportedDropCount, dropped)) { - Report($"[{_name}] {dropped} logging event(s) in total were not sent.", null); + Report($"[{_name}] {dropped} message(s) in total were not sent.", null); } } @@ -259,11 +264,12 @@ private void Pump() try { _send(item.Payload!, _shutdown.Token); + _isCongested = false; } catch (Exception e) when (!e.IsFatal()) { CountLost(); - Report($"[{_name}] Failed to send a logging event.", e); + Report($"[{_name}] Failed to send a message.", e); } } } @@ -321,7 +327,7 @@ private void ReportQueueFull() CountLost(); if (Interlocked.Exchange(ref _dropReported, 1) == 0) { - Report($"[{_name}] A logging event was dropped: the queue is full or closed. " + Report($"[{_name}] A message was dropped: the queue is full or closed. " + "Further losses are counted and reported when the sender closes.", null); } } 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 b35d314b0..0c06df752 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 @@ -40,20 +40,20 @@ The following example sends all events with Level WARN or higher to the remote s You can also specify: -* Facility (default: user) -* Identity (default: application name) -* SendQueueSize (default: 500), how many datagrams may wait to be sent -* EnqueueTimeoutMillis (default: 5000), how long a logging call waits for room in a full queue -* MaxDatagramSize (default: 65507), the largest datagram sent, inherited from the xref:./udpappender.adoc[] +* facility (default: user) +* identity (default: application name) +* sendQueueSize (default: 500), how many datagrams may wait to be sent +* enqueueTimeoutMillis (default: 5000), how long a logging call waits for room in a full queue +* maxDatagramSize (default: 65507), the largest datagram sent, inherited from the xref:./udpappender.adoc[] RFC 3164 allows only the visible ASCII characters and space in the message, so anything else is written as a `\uXXXX` escape rather than dropped: a message in a non-Latin script reaches the collector readable instead of empty. `Encoding` therefore does not make the message body non-ASCII. -Datagrams are handed to a background thread, so a slow or unreachable syslog server does not hold -up logging. Once the queue is full, a logging call waits `EnqueueTimeoutMillis` for room and the -datagram is then discarded and counted, rather than growing the queue without limit. `Flush` waits -for the queue to drain. +:sender-sink: syslog server +:sender-item: datagram +:sender-items: datagrams +include::partial$background-sender.adoc[] [source,xml] ---- diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/smtpappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/smtpappender.adoc index 29977db66..1b1787d5f 100644 --- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/smtpappender.adoc +++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/smtpappender.adoc @@ -230,7 +230,6 @@ Quoted-printable can triple the size on the wire. The legacy appender has the sa |`enqueueTimeoutMillis` |How long a logging call waits for room in a full queue, in milliseconds. Defaults to `5000`. -`0` never waits and discards the mail instead. |`bufferSize` |How many log events to buffer into one email. See xref:manual/configuration/appenders.adoc[]. @@ -244,6 +243,11 @@ Quoted-printable can triple the size on the wire. The legacy appender has the sa `to`, `cc` and `bcc` also accept semicolons as separators, and quoted display names such as `"Doe, John" `. +:sender-sink: SMTP server +:sender-item: mail +:sender-items: mails +include::partial$background-sender.adoc[] + [#mailkit-smtpappender-transport-security] === Transport security @@ -299,10 +303,9 @@ MailKit cannot reuse the Windows logon session of the current thread or process, * `transportSecurity` has no counterpart in the legacy appender, which offers only `enableSsl`. * `sendTimeoutMillis` is a deadline for the whole send here, while in the legacy appender it bounds the one `SmtpClient.Send` call. Both default to `15000`. -* The mail is handed to a background thread rather than sent by the thread that logged, so a slow -server no longer stalls logging. Failures are reported to the error handler as before, but after -the logging call has returned, and mail still queued is lost if the process is killed. -`sendQueueSize` and `enqueueTimeoutMillis` bound the queue. +* The mail is sent from a background thread rather than by the thread that logged, see +<>. Failures are reported to the error handler as before, but after +the logging call has returned. `enableSsl` keeps its meaning but not its default: it is `true` here and `false` in the legacy appender, so a configuration that set neither option now requires transport security. 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 9e01eade6..c86f31854 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 @@ -72,16 +72,18 @@ how long a client that stopped reading holds up the stream before it is dropped. How many rendered events may wait to be written to the clients. The default is `500`. + -A full queue drops the event from the telnet stream, counted and reported once. -Only the telnet view is lost; every other appender still receives the event. +A full queue drops the event from the telnet stream only; every other appender still receives it. `enqueueTimeoutMillis`:: How long, in milliseconds, a logging call may wait for room in the send queue. The default is `50`. + This is the only delay a client can impose on the application. -While the queue stays full it caps logging at 20 events per second; `0` drops immediately instead -of waiting. + +:sender-sink: client +:sender-item: event +:sender-items: events +include::partial$background-sender.adoc[] [#telnetappender-trust] == Intended use and trust model diff --git a/src/site/antora/modules/ROOT/partials/background-sender.adoc b/src/site/antora/modules/ROOT/partials/background-sender.adoc new file mode 100644 index 000000000..6f7527dc6 --- /dev/null +++ b/src/site/antora/modules/ROOT/partials/background-sender.adoc @@ -0,0 +1,24 @@ +//// + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +//// + +Sending happens on a background thread, so a slow or unresponsive {sender-sink} does not hold up +logging. Up to `sendQueueSize` {sender-items} wait in a queue. When it is full, a logging call waits +up to `enqueueTimeoutMillis` for room and discards its {sender-item} if none frees up. After such a +timeout, later calls discard without waiting until a send succeeds; `0` never waits. Discarded +{sender-items} are counted: the first is reported to the error handler at once, the total when the +appender closes. `Flush` waits for the queue to drain; {sender-items} still queued are lost if the +process is killed. From 58291fc747b6889492d1bca8efa0e1fd8d012693 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 19:15:22 +0100 Subject: [PATCH 3/6] #371 Send a syslog record once more after a socket error - ANT-2026-C2Q2AQZL - the error may belong to the datagram before, on Linux - docs on maxDatagramSize behind a router with a smaller MTU --- .../3.6.1/371-icmp-error-costs-no-record.xml | 11 ++ .../Appender/Internal/UdpMock.cs | 10 + .../Appender/RemoteSyslogAppenderTest.cs | 180 ++++++++++++++++++ src/log4net/Appender/RemoteSyslogAppender.cs | 32 +++- src/log4net/Appender/UdpAppender.cs | 4 +- .../appenders/remotesyslogappender.adoc | 6 +- .../configuration/appenders/udpappender.adoc | 3 +- 7 files changed, 241 insertions(+), 5 deletions(-) create mode 100644 src/changelog/3.6.1/371-icmp-error-costs-no-record.xml diff --git a/src/changelog/3.6.1/371-icmp-error-costs-no-record.xml b/src/changelog/3.6.1/371-icmp-error-costs-no-record.xml new file mode 100644 index 000000000..717e1c36e --- /dev/null +++ b/src/changelog/3.6.1/371-icmp-error-costs-no-record.xml @@ -0,0 +1,11 @@ + + + + + `RemoteSyslogAppender` sends a record once more when the send reports a + socket error, which on Linux may belong to the datagram before it. A record is no longer lost to the + ICMP error of the one before it; the error is reported (ANT-2026-C2Q2AQZL, fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Appender/Internal/UdpMock.cs b/src/log4net.Tests/Appender/Internal/UdpMock.cs index 3d06e74f1..927316e92 100644 --- a/src/log4net.Tests/Appender/Internal/UdpMock.cs +++ b/src/log4net.Tests/Appender/Internal/UdpMock.cs @@ -50,6 +50,11 @@ internal sealed class UdpMock : IUdpConnection /// internal Exception? ConnectException { get; set; } + /// + /// Each send takes the next of these, if any, and throws it instead of sending. + /// + internal Queue SendExceptions { get; } = new(); + /// public void Connect(int localPort, IPAddress host, int remotePort) { @@ -66,6 +71,11 @@ public void Connect(int localPort, IPAddress host, int remotePort) /// public Task SendAsync(byte[] datagram, int bytes) { + if (SendExceptions.Count > 0) + { + throw SendExceptions.Dequeue(); + } + Sent.Add((datagram, bytes)); return Task.FromResult(bytes); } diff --git a/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs b/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs index e5fd6760f..44ae0eddb 100644 --- a/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs +++ b/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs @@ -20,6 +20,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; +using System.Net.Sockets; using System.Text; using log4net.Appender; using log4net.Appender.Internal; @@ -297,6 +299,184 @@ public void IdentityWithoutControlCharactersIsUnchangedAndNotReported() Assert.That(messages.ConvertAll(m => m.Message), Has.None.Contains("Identity of appender")); } + /// + /// A socket error may belong to an earlier datagram, so the record is sent once more and the error reported. + /// + [Test] + public void ASocketErrorIsAnsweredWithOneMoreSend() + { + RecordingErrorHandler errorHandler = new(); + RemoteAppender appender = CreateMockAppender(errorHandler, new SocketException((int)SocketError.ConnectionRefused)); + + appender.DoAppend(CreateEvent("record")); + appender.Close(); + + Assert.That(appender.Mock.Sent, Has.Count.EqualTo(1)); + Assert.That(errorHandler.Messages, Is.EqualTo(new[] { SentAgainMessage })); + } + + /// + /// A second error is the record's own: it is lost and counted, as any failed send. + /// + [Test] + public void ASecondSocketErrorLosesTheRecord() + { + RecordingErrorHandler errorHandler = new(); + RemoteAppender appender = CreateMockAppender(errorHandler, + new SocketException((int)SocketError.ConnectionRefused), new SocketException((int)SocketError.ConnectionRefused)); + + appender.DoAppend(CreateEvent("record")); + appender.Close(); + + Assert.That(appender.Mock.Sent, Is.Empty); + Assert.That(errorHandler.Messages, Is.EqualTo(_lostRecordMessages)); + } + + /// + /// Only a socket error can stand for an earlier datagram. + /// + [Test] + public void AnotherErrorIsNotAnsweredWithASecondSend() + { + RecordingErrorHandler errorHandler = new(); + RemoteAppender appender = CreateMockAppender(errorHandler, new InvalidOperationException("simulated send failure")); + + appender.DoAppend(CreateEvent("record")); + appender.Close(); + + Assert.That(appender.Mock.Sent, Is.Empty); + Assert.That(errorHandler.Messages, Is.EqualTo(_lostRecordMessages)); + } + + /// + /// An error handler that throws while told about the second send must not get the sent record counted as lost. + /// + [Test] + [NonParallelizable] + public void AThrowingErrorHandlerDoesNotLoseASentRecord() + { + ThrowingErrorHandler errorHandler = new(); + RemoteAppender appender = CreateMockAppender(errorHandler, new SocketException((int)SocketError.ConnectionRefused)); + + LogLog.ExecuteWithoutEmittingInternalMessages(() => + { + appender.DoAppend(CreateEvent("record")); + appender.Close(); + }); + + Assert.That(appender.Mock.Sent, Has.Count.EqualTo(1)); + Assert.That(errorHandler.Messages, Is.EqualTo(new[] { SentAgainMessage })); + } + + /// + /// On Linux the ICMP error of a datagram to a closed port is returned by the next send, which then + /// transmits nothing. The next record must still arrive. + /// + [Test] + [Platform("Linux")] + public void TheRecordAfterAnIcmpErrorArrives() + { + int port = ReserveLoopbackPort(); + RecordingErrorHandler errorHandler = new(); + RemoteSyslogAppender appender = new() + { + RemoteAddress = IPAddress.Loopback, + RemotePort = port, + Layout = new PatternLayout("%message"), + ErrorHandler = errorHandler + }; + appender.ActivateOptions(); + try + { + appender.DoAppend(CreateEvent("earlier")); + Assert.That(appender.Flush(FlushTimeoutMillis), Is.True); + Socket socket = appender.GetFieldValue("_connection").GetFieldValue("_client").Client; + if (!socket.Poll(5_000_000, SelectMode.SelectError)) + { + Assert.Ignore("No ICMP error arrived on loopback."); + } + + using UdpClient collector = new(new IPEndPoint(IPAddress.Loopback, port)); + collector.Client.ReceiveTimeout = FlushTimeoutMillis; + appender.DoAppend(CreateEvent("next")); + Assert.That(appender.Flush(FlushTimeoutMillis), Is.True); + + IPEndPoint? sender = null; + Assert.That(Encoding.ASCII.GetString(collector.Receive(ref sender)), Does.EndWith("next")); + } + finally + { + appender.Close(); + } + } + + private const string SentAgainMessage = """ + A send to remote syslog 127.0.0.1 on port 514 reported an error, + possibly for an earlier datagram; sent again. + """; + + private static readonly string[] _lostRecordMessages = + [ + "[RemoteSyslogAppender] Failed to send a message.", + "[RemoteSyslogAppender] 1 message(s) in total were not sent." + ]; + + private static RemoteAppender CreateMockAppender(IErrorHandler errorHandler, params Exception[] sendExceptions) + { + RemoteAppender appender = new() + { + RemoteAddress = new IPAddress([127, 0, 0, 1]), + Layout = new PatternLayout("%message"), + ErrorHandler = errorHandler + }; + foreach (Exception exception in sendExceptions) + { + appender.Mock.SendExceptions.Enqueue(exception); + } + + appender.ActivateOptions(); + return appender; + } + + private static LoggingEvent CreateEvent(string message) + => new(new() { Level = Level.Info, Message = message, LoggerName = "TestLogger" }); + + /// + /// A loopback port that was free a moment ago, so nothing listens on it. + /// + private static int ReserveLoopbackPort() + { + using UdpClient probe = new(new IPEndPoint(IPAddress.Loopback, 0)); + return ((IPEndPoint)probe.Client.LocalEndPoint!).Port; + } + + /// + /// Records each message, then throws. + /// + private sealed class ThrowingErrorHandler : IErrorHandler + { + internal List Messages { get; } = []; + + /// + public void Error(string message) => Record(message); + + /// + public void Error(string message, Exception e) => Record(message); + + /// + public void Error(string message, Exception? e, ErrorCode errorCode) => Record(message); + + private void Record(string message) + { + lock (Messages) + { + Messages.Add(message); + } + + throw new InvalidOperationException("simulated error handler failure"); + } + } + private static List ExecuteAppend(string message, SyslogNewLineHandling newLineHandling = default, string? identity = null, diff --git a/src/log4net/Appender/RemoteSyslogAppender.cs b/src/log4net/Appender/RemoteSyslogAppender.cs index bc1aa14b6..ac320de62 100644 --- a/src/log4net/Appender/RemoteSyslogAppender.cs +++ b/src/log4net/Appender/RemoteSyslogAppender.cs @@ -19,6 +19,7 @@ using System; using System.Globalization; +using System.Net.Sockets; using System.Text; using System.Threading; using log4net.Appender.Internal; @@ -258,6 +259,7 @@ public enum SyslogFacility } private const int CloseTimeoutMillis = 5_000; + private static readonly Type _declaringType = typeof(RemoteSyslogAppender); private IUdpConnection? _connection; private BackgroundSender? _sender; private int _sendQueueSize = 500; @@ -572,7 +574,35 @@ public int EnqueueTimeoutMillis } private void Send(byte[] datagram, CancellationToken cancellationToken) - => _connection?.SendAsync(datagram, datagram.Length).GetAwaiter().GetResult(); + { + // StopSending clears the field while a stuck pump may still run. + if (_connection is not IUdpConnection connection) + { + return; + } + + try + { + connection.SendAsync(datagram, datagram.Length).GetAwaiter().GetResult(); + } + catch (SocketException e) + { + // On Linux a send can return the ICMP error of an earlier datagram and transmit nothing. + connection.SendAsync(datagram, datagram.Length).GetAwaiter().GetResult(); + try + { + Report($""" + A send to remote syslog {RemoteAddress} on port {RemotePort} reported an error, + possibly for an earlier datagram; sent again. + """, e); + } + catch (Exception reportFailure) when (!reportFailure.IsFatal()) + { + // The record went out, so the pump must not count it lost. + LogLog.Error(_declaringType, "The error handler threw.", reportFailure); + } + } + } private void Report(string message, Exception? exception) { diff --git a/src/log4net/Appender/UdpAppender.cs b/src/log4net/Appender/UdpAppender.cs index 84121f618..15d37f664 100644 --- a/src/log4net/Appender/UdpAppender.cs +++ b/src/log4net/Appender/UdpAppender.cs @@ -249,8 +249,8 @@ public Encoding Encoding /// A value from 512 to 65507, the maximum UDP payload of an IPv4 packet. Default 65507. /// /// The socket rejects a larger datagram, so a longer event is truncated to fit instead of lost. - /// Lower the value to match a receiver that accepts less. IPv6 would carry 20 bytes more, which - /// is not worth a second limit. + /// Lower the value to the receiver's limit, or to the path MTU minus 28 where a hop has a smaller + /// MTU. IPv6 would carry 20 bytes more, which is not worth a second limit. /// /// The value specified is outside 512 to 65507. public int MaxDatagramSize 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 0c06df752..b5e167dbf 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 @@ -146,4 +146,8 @@ However, there are size limitations associated with UDP: * **Practical size limit:** On many networks, such as Ethernet, the practical limit for message size is typically much lower, around **1500 bytes**. * **Message truncation:** If a log message exceeds these size limits, it will be **truncated**, which means some of the message content will be lost. -To avoid truncation, ensure that log messages are kept within the size limits of your network setup. \ No newline at end of file +To avoid truncation, ensure that log messages are kept within the size limits of your network setup. + +On Linux, a router with a smaller MTU than the sending host drops a datagram that fits the host but +not the router, at most once every 10 minutes. The appender resends the record after it, so only that +one is lost. To avoid this, set `maxDatagramSize` to the router's MTU minus 28 (IPv4). diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/udpappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/udpappender.adoc index 0975a2b98..1e8f5c281 100644 --- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/udpappender.adoc +++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/udpappender.adoc @@ -39,7 +39,8 @@ The following example shows how to configure the `UdpAppender` to send events to An event that does not fit one datagram is truncated and marked with `...[truncated]` rather than dropped: the socket rejects a payload above `MaxDatagramSize` (default 65507, the maximum UDP payload of an IPv4 packet), and that used to cost the whole event. Lower `MaxDatagramSize`, down to -512, to match a receiver that accepts less. It cannot be raised: an IPv6 packet would carry 20 bytes +512, to match a receiver that accepts less, or to the path MTU minus 28 where a hop has a smaller +MTU (measured with `RemoteSyslogAppender`). It cannot be raised: an IPv6 packet would carry 20 bytes more, which is not worth a second limit. The default `Encoding` is UTF-8 on .NET and the system's ANSI code page on .NET Framework; the receiver has to decode with the same encoding, so set it explicitly. From 1ebe600ce7ab97ccbe2bd25c351e52b35e915086 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 19:29:38 +0100 Subject: [PATCH 4/6] #372 Reject an undefined NewLineHandling in LocalSyslogAppender - ANT-2026-6O92ZO65 - a value set after ActivateOptions escapes instead of keeping the line breaks --- ...72-undefined-newline-handling-rejected.xml | 12 +++++ .../Appender/LocalSyslogAppenderTest.cs | 51 +++++++++++++++++++ src/log4net/Appender/LocalSyslogAppender.cs | 10 +++- .../appenders/localsyslogappender.adoc | 3 +- 4 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 src/changelog/3.6.1/372-undefined-newline-handling-rejected.xml diff --git a/src/changelog/3.6.1/372-undefined-newline-handling-rejected.xml b/src/changelog/3.6.1/372-undefined-newline-handling-rejected.xml new file mode 100644 index 000000000..e723f7b0d --- /dev/null +++ b/src/changelog/3.6.1/372-undefined-newline-handling-rejected.xml @@ -0,0 +1,12 @@ + + + + + `LocalSyslogAppender` rejects a `NewLineHandling` other than `Escape`, + `Split` or `Keep` on activation, as `RemoteSyslogAppender` does, so the appender logs nothing. A + configuration with a number such as `5` ran as `Keep` until now, with raw line breaks + (ANT-2026-6O92ZO65, fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs index 402cbdb81..515a081c1 100644 --- a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs +++ b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs @@ -140,6 +140,57 @@ public void NewLineHandlingDefaultsToEscape() => Assert.That(new LocalSyslogAppender().NewLineHandling, Is.EqualTo(SyslogNewLineHandling.Escape)); + /// + /// newLineHandling binds through , which accepts any number, so an + /// undefined value must not turn the escaping off unnoticed. + /// + [TestCase(3)] + [TestCase(5)] + [TestCase(-1)] + public void AnUndefinedNewLineHandlingIsRejected(int value) + { + LocalSyslogAppender appender = new() { NewLineHandling = (SyslogNewLineHandling)value }; + + Assert.That(appender.ActivateOptions, Throws.TypeOf()); + } + + /// Each defined value passes the check. + [TestCase(SyslogNewLineHandling.Keep)] + [TestCase(SyslogNewLineHandling.Split)] + [TestCase(SyslogNewLineHandling.Escape)] + [Platform("Linux")] + [NonParallelizable] + public void EveryDefinedNewLineHandlingIsAccepted(SyslogNewLineHandling value) + { + LocalSyslogAppender appender = new() + { + NewLineHandling = value, + Identity = "log4net-test", + Layout = new PatternLayout("%message") + }; + + Assert.That(appender.ActivateOptions, Throws.Nothing); + appender.Close(); + } + + /// An undefined value set after activation escapes, as the default does. + [Test] + public void AnUndefinedNewLineHandlingEscapes() + { + LocalSyslogAppender appender = new() { NewLineHandling = (SyslogNewLineHandling)5 }; + + Assert.That(GetRecords(appender, "a\nb"), Is.EqualTo(new[] { "a\\nb" })); + } + + /// passes the newlines through. + [Test] + public void KeepLeavesTheNewLines() + { + LocalSyslogAppender appender = new() { NewLineHandling = SyslogNewLineHandling.Keep }; + + Assert.That(GetRecords(appender, "a\nb"), Is.EqualTo(new[] { "a\nb" })); + } + /// One record per line, and a blank line is no record at all. [Test] public void SplittingDropsTheEmptyLines() diff --git a/src/log4net/Appender/LocalSyslogAppender.cs b/src/log4net/Appender/LocalSyslogAppender.cs index cf01cc883..0804b7b9f 100644 --- a/src/log4net/Appender/LocalSyslogAppender.cs +++ b/src/log4net/Appender/LocalSyslogAppender.cs @@ -301,6 +301,11 @@ public enum SyslogFacility public override void ActivateOptions() { base.ActivateOptions(); + if (NewLineHandling is not (SyslogNewLineHandling.Escape or SyslogNewLineHandling.Keep or SyslogNewLineHandling.Split)) + { + throw SystemInfo.CreateArgumentOutOfRangeException(nameof(NewLineHandling), NewLineHandling, + $"The NewLineHandling is not {SyslogNewLineHandling.Escape} or {SyslogNewLineHandling.Keep} or {SyslogNewLineHandling.Split}."); + } _levelMapping.ActivateOptions(); @@ -373,8 +378,9 @@ private string[] GetRecords(string message) string[] records = NewLineHandling switch { SyslogNewLineHandling.Split => SplitLines(message), - SyslogNewLineHandling.Escape => [EscapeNewLines(message)], - _ => [message] + SyslogNewLineHandling.Keep => [message], + // Escape, also for undefined values. + _ => [EscapeNewLines(message)] }; for (int i = 0; i < records.Length; i++) 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 e5de62757..50a0363c6 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 @@ -38,7 +38,8 @@ You can also specify: * Facility (default: user) * Identity (default: application name) -* NewLineHandling (default: Escape), one of `Escape`, `Split` or `Keep` +* NewLineHandling (default: Escape), one of `Escape`, `Split` or `Keep`; any other value fails the +appender's activation with an error * MaxRecordSize (default: 204800), in UTF-8 bytes, at least 512 A newline in logged content ends the record for a syslog daemon that writes the message through to From 8547418bd32d454d2cf953bc60d18803a83fbaa9 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 19:37:33 +0100 Subject: [PATCH 5/6] #372 Escape the other line breaks in LocalSyslogAppender - ANT-2026-1YRNCBP9 - VT, FF, FS, GS, RS, NEL, U+2028 and U+2029 as \uXXXX in Escape and Split --- .../3.6.1/372-other-line-breaks-escaped.xml | 11 +++++ .../Appender/LocalSyslogAppenderTest.cs | 43 +++++++++++++++++++ .../Appender/Internal/ContentEscape.cs | 31 +++++++++++++ src/log4net/Appender/LocalSyslogAppender.cs | 4 +- .../appenders/localsyslogappender.adoc | 12 +++--- 5 files changed, 94 insertions(+), 7 deletions(-) create mode 100644 src/changelog/3.6.1/372-other-line-breaks-escaped.xml diff --git a/src/changelog/3.6.1/372-other-line-breaks-escaped.xml b/src/changelog/3.6.1/372-other-line-breaks-escaped.xml new file mode 100644 index 000000000..e4182e904 --- /dev/null +++ b/src/changelog/3.6.1/372-other-line-breaks-escaped.xml @@ -0,0 +1,11 @@ + + + + + `LocalSyslogAppender` with `NewLineHandling` `Escape` or `Split` writes + VT, FF, FS, GS, RS, NEL, U+2028 and U+2029 as `\uXXXX`, like CR and LF, so a reader that breaks lines + there no longer shows one record as two (ANT-2026-1YRNCBP9, fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs index 515a081c1..31fc0c39e 100644 --- a/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs +++ b/src/log4net.Tests/Appender/LocalSyslogAppenderTest.cs @@ -191,6 +191,49 @@ public void KeepLeavesTheNewLines() Assert.That(GetRecords(appender, "a\nb"), Is.EqualTo(new[] { "a\nb" })); } + /// + /// A reader may break a line at these too, so and + /// escape them; passes them. + /// + [TestCase("a\vb", "a\\u000bb", TestName = "OtherLineBreaksAreEscapedUnlessKept(VT)")] + [TestCase("a\fb", "a\\u000cb", TestName = "OtherLineBreaksAreEscapedUnlessKept(FF)")] + [TestCase("a\u001cb", "a\\u001cb", TestName = "OtherLineBreaksAreEscapedUnlessKept(FS)")] + [TestCase("a\u001db", "a\\u001db", TestName = "OtherLineBreaksAreEscapedUnlessKept(GS)")] + [TestCase("a\u001eb", "a\\u001eb", TestName = "OtherLineBreaksAreEscapedUnlessKept(RS)")] + [TestCase("a\u2028b", "a\\u2028b", TestName = "OtherLineBreaksAreEscapedUnlessKept(LS)")] + [TestCase("a\u2029b", "a\\u2029b", TestName = "OtherLineBreaksAreEscapedUnlessKept(PS)")] + [TestCase("a\u0085b", "a\\u0085b", TestName = "OtherLineBreaksAreEscapedUnlessKept(NEL)")] + public void OtherLineBreaksAreEscapedUnlessKept(string message, string expected) + { + Assert.That(GetRecords(new() { NewLineHandling = SyslogNewLineHandling.Escape }, message), + Is.EqualTo(new[] { expected })); + Assert.That(GetRecords(new() { NewLineHandling = SyslogNewLineHandling.Split }, message), + Is.EqualTo(new[] { expected })); + Assert.That(GetRecords(new() { NewLineHandling = SyslogNewLineHandling.Keep }, message), + Is.EqualTo(new[] { message })); + } + + /// escapes every line, not only the first. + [Test] + public void SplitEscapesEveryLine() + => Assert.That(GetRecords(new() { NewLineHandling = SyslogNewLineHandling.Split }, "a\vb\nc\u2028d"), + Is.EqualTo(new[] { "a\\u000bb", "c\\u2028d" })); + + /// The escape comes before the cut, so the escaped record still fits the limit. + [Test] + public void OtherLineBreaksAreEscapedBeforeTheCut() + { + LocalSyslogAppender appender = new() { MaxRecordSize = 512, ErrorHandler = new RecordingErrorHandler() }; + + Assert.That(GetRecords(appender, new string('\v', 100)), + Is.EqualTo(new[] { string.Concat(Enumerable.Repeat("\\u000b", 83)) + "...[truncated]" })); + } + + /// Tab and text outside ASCII are no line breaks. + [Test] + public void TabAndNonAsciiTextAreUnchanged() + => Assert.That(GetRecords(new(), "a\tb \u00e4\u3042"), Is.EqualTo(new[] { "a\tb \u00e4\u3042" })); + /// One record per line, and a blank line is no record at all. [Test] public void SplittingDropsTheEmptyLines() diff --git a/src/log4net/Appender/Internal/ContentEscape.cs b/src/log4net/Appender/Internal/ContentEscape.cs index 0c8a7e495..104aaefe8 100644 --- a/src/log4net/Appender/Internal/ContentEscape.cs +++ b/src/log4net/Appender/Internal/ContentEscape.cs @@ -86,6 +86,35 @@ internal string EscapeUnpairedSurrogates() return builder.ToString(); } + /// + /// Replaces the line breaks other than CR and LF with a visible \uXXXX escape: VT, FF, FS, + /// GS, RS, NEL, U+2028 and U+2029. + /// + /// The message with every such line break escaped. + /// A reader that breaks lines at them would show one record as two. + internal string EscapeOtherLineBreaks() + { + if (message.IndexOfAny(_otherLineBreaks) < 0) + { + return message; + } + + StringBuilder builder = new(message.Length + 16); + foreach (char c in message) + { + if (Array.IndexOf(_otherLineBreaks, c) >= 0) + { + builder.Append(Escape(c)); + } + else + { + builder.Append(c); + } + } + + return builder.ToString(); + } + /// /// Replaces a CR that is not followed by LF with a visible \r escape; a CRLF stays. /// @@ -169,6 +198,8 @@ internal string FormatWithEscapedSurrogates(LoggingEvent loggingEvent) => layout.Format(loggingEvent).EscapeUnpairedSurrogates(); } + private static readonly char[] _otherLineBreaks = ['\v', '\f', '\x1c', '\x1d', '\x1e', '\u0085', '\u2028', '\u2029']; + /// A CR that is not followed by LF. private static readonly Regex _loneCarriageReturn = new("\r(?!\n)", RegexOptions.Compiled); diff --git a/src/log4net/Appender/LocalSyslogAppender.cs b/src/log4net/Appender/LocalSyslogAppender.cs index 0804b7b9f..2f373a827 100644 --- a/src/log4net/Appender/LocalSyslogAppender.cs +++ b/src/log4net/Appender/LocalSyslogAppender.cs @@ -377,10 +377,10 @@ private string[] GetRecords(string message) { string[] records = NewLineHandling switch { - SyslogNewLineHandling.Split => SplitLines(message), + SyslogNewLineHandling.Split => Array.ConvertAll(SplitLines(message), line => line.EscapeOtherLineBreaks()), SyslogNewLineHandling.Keep => [message], // Escape, also for undefined values. - _ => [EscapeNewLines(message)] + _ => [EscapeNewLines(message).EscapeOtherLineBreaks()] }; for (int i = 0; i < records.Length; i++) 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 50a0363c6..9e06ab59b 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 @@ -42,11 +42,13 @@ You can also specify: appender's activation with an error * MaxRecordSize (default: 204800), in UTF-8 bytes, at least 512 -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. 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. +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, +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. glibc sends each record as one datagram to `/dev/log` and drops it without a word when it is larger than the socket send buffer, 212960 bytes with the default `net.core.wmem_default`. A record longer From 00752739050dfa936c494cd9ed959004ece3f4d8 Mon Sep 17 00:00:00 2001 From: Jan Friedrich Date: Sun, 22 Nov 2026 20:01:21 +0100 Subject: [PATCH 6/6] #372 Name the parameter of CreateArgumentOutOfRangeException from the caller - CallerArgumentExpression, hidden from IntelliSense, signature breaks on purpose - all 32 call sites drop the name - ValidateIndex reports "index" instead of "i" --- AGENTS.md | 2 ++ .../372-argument-range-name-from-caller.xml | 11 ++++++++++ .../Appender/SmtpAppenderTest.cs | 3 ++- src/log4net.Ext.Mail/Appender/SmtpAppender.cs | 10 ++++----- .../Appender/AppenderCollectionTest.cs | 13 +++++++++++ src/log4net.Tests/Core/LevelMapTest.cs | 13 ++++++++++- src/log4net.Tests/Util/SystemInfoTest.cs | 22 ++++++++++++++++++- src/log4net/Appender/AppenderCollection.cs | 12 +++++----- src/log4net/Appender/FileAppender.cs | 2 +- src/log4net/Appender/LocalSyslogAppender.cs | 4 ++-- src/log4net/Appender/RemoteSyslogAppender.cs | 6 ++--- src/log4net/Appender/RollingFileAppender.cs | 2 +- src/log4net/Appender/SmtpAppender.cs | 4 ++-- src/log4net/Appender/TelnetAppender.cs | 8 +++---- src/log4net/Appender/UdpAppender.cs | 10 ++++----- src/log4net/Core/DefaultRepositorySelector.cs | 2 +- src/log4net/Core/LevelCollection.cs | 18 +++++++-------- src/log4net/Core/LevelMap.cs | 2 +- src/log4net/Filter/StringMatchFilter.cs | 4 ++-- src/log4net/Plugin/PluginCollection.cs | 16 +++++++------- src/log4net/Util/CyclicBuffer.cs | 4 ++-- src/log4net/Util/SystemInfo.cs | 22 ++++++++++--------- 22 files changed, 125 insertions(+), 65 deletions(-) create mode 100644 src/changelog/3.6.1/372-argument-range-name-from-caller.xml diff --git a/AGENTS.md b/AGENTS.md index d2f2f2889..939a3c933 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,6 +74,8 @@ almost always be doing. `[CallerArgumentExpression(nameof(value))]`, so no argument name is passed at the call site. This includes constructor and property assignments: write `_x = x.EnsureNotNull();`, not `_x = x ?? throw new ArgumentNullException(nameof(x));`. +- `SystemInfo.CreateArgumentOutOfRangeException(value, message)` names the parameter the same way: + pass the value itself, never a name. - Appenders never let exceptions escape to the caller. The house pattern is `catch (Exception e) when (!e.IsFatal()) { ErrorHandler.Error("...", e); }`. - **A catch of `Exception` always carries `when (!e.IsFatal())`.** The filter is not a licence to diff --git a/src/changelog/3.6.1/372-argument-range-name-from-caller.xml b/src/changelog/3.6.1/372-argument-range-name-from-caller.xml new file mode 100644 index 000000000..8837ecf1f --- /dev/null +++ b/src/changelog/3.6.1/372-argument-range-name-from-caller.xml @@ -0,0 +1,11 @@ + + + + + `SystemInfo.CreateArgumentOutOfRangeException` takes the parameter name + from the expression passed as the value and is hidden from IntelliSense. Code compiled against an + older log4net that calls it has to be rebuilt (implemented by @FreeAndNil) + diff --git a/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs b/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs index 5f0fa0b5a..73fb34ad2 100644 --- a/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs +++ b/src/log4net.Ext.Mail.Tests/Appender/SmtpAppenderTest.cs @@ -888,7 +888,8 @@ public void EnqueueTimeoutMillisDefaultsTo5000() [TestCase(-1)] public void SendQueueSizeRejectsValuesThatAreNotPositive(int value) => Assert.That(() => CreateAppender().SendQueueSize = value, - Throws.TypeOf()); + Throws.TypeOf() + .With.Property(nameof(ArgumentOutOfRangeException.ParamName)).EqualTo("value")); /// 0 is allowed and never waits, a negative wait is meaningless. [Test] diff --git a/src/log4net.Ext.Mail/Appender/SmtpAppender.cs b/src/log4net.Ext.Mail/Appender/SmtpAppender.cs index b4916779e..a869ca2a6 100644 --- a/src/log4net.Ext.Mail/Appender/SmtpAppender.cs +++ b/src/log4net.Ext.Mail/Appender/SmtpAppender.cs @@ -367,7 +367,7 @@ public int MaxBodySize { if (value < MailBodies.MinBodySize) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {MailBodies.MinBodySize}."); } field = value; @@ -439,7 +439,7 @@ public int SendQueueSize { if (value <= 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendQueueSize is not positive."); } _sendQueueSize = value; @@ -460,7 +460,7 @@ public int EnqueueTimeoutMillis { if (value < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for EnqueueTimeoutMillis is negative."); } _enqueueTimeoutMillis = value; @@ -520,7 +520,7 @@ private void Report(string message, Exception? exception) SmtpTransportSecurity.ImplicitTls => SecureSocketOptions.SslOnConnect, SmtpTransportSecurity.StartTls => SecureSocketOptions.StartTls, SmtpTransportSecurity.StartTlsWhenAvailable => SecureSocketOptions.StartTlsWhenAvailable, - _ => throw SystemInfo.CreateArgumentOutOfRangeException(nameof(TransportSecurity), TransportSecurity, + _ => throw SystemInfo.CreateArgumentOutOfRangeException(TransportSecurity, $"The value specified for TransportSecurity is not one of the {nameof(SmtpTransportSecurity)} values.") }; @@ -575,7 +575,7 @@ public int SendTimeoutMillis { if (value <= 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendTimeoutMillis is not positive."); } _sendTimeoutMillis = value; diff --git a/src/log4net.Tests/Appender/AppenderCollectionTest.cs b/src/log4net.Tests/Appender/AppenderCollectionTest.cs index 1b982e492..56f1844e4 100644 --- a/src/log4net.Tests/Appender/AppenderCollectionTest.cs +++ b/src/log4net.Tests/Appender/AppenderCollectionTest.cs @@ -61,4 +61,17 @@ public void ReadOnlyToArrayTest() Assert.That(appenderArray, Has.Length.EqualTo(1)); Assert.That(appenderArray[0], Is.EqualTo(appender)); } + + /// + /// An index out of range is reported under the name of the indexer's parameter. + /// + [Test] + public void AnIndexOutOfRangeNamesTheIndex() + { + AppenderCollection appenderCollection = []; + + Assert.That(() => appenderCollection[-1], + Throws.TypeOf() + .With.Property(nameof(System.ArgumentOutOfRangeException.ParamName)).EqualTo("index")); + } } \ No newline at end of file diff --git a/src/log4net.Tests/Core/LevelMapTest.cs b/src/log4net.Tests/Core/LevelMapTest.cs index 30f6131f7..3d99b9cd3 100644 --- a/src/log4net.Tests/Core/LevelMapTest.cs +++ b/src/log4net.Tests/Core/LevelMapTest.cs @@ -17,6 +17,8 @@ // #endregion +using System; + using log4net.Core; using NUnit.Framework; @@ -64,4 +66,13 @@ public void LevelMapCreateClear() Assert.That(map["level1234"], Is.Null); Assert.That(map["LEVEL5678"], Is.Null); } -} \ No newline at end of file + + /// + /// The name is a string, so a call that still passes it twice would compile with the arguments shifted. + /// + [Test] + public void AnEmptyLevelNameNamesItsParameter() + => Assert.That(() => new LevelMap().Add(string.Empty, 1, null), + Throws.TypeOf() + .With.Property(nameof(ArgumentOutOfRangeException.ParamName)).EqualTo("name")); +} diff --git a/src/log4net.Tests/Util/SystemInfoTest.cs b/src/log4net.Tests/Util/SystemInfoTest.cs index 7996258f4..14899dc4e 100644 --- a/src/log4net.Tests/Util/SystemInfoTest.cs +++ b/src/log4net.Tests/Util/SystemInfoTest.cs @@ -330,4 +330,24 @@ private static bool AppSettingsUnavailable } private const string FlagField = "_configurationSystemUnavailable"; -} \ No newline at end of file + + /// The compiler names the parameter after the expression passed as the value. + [Test] + public void TheParameterIsNamedAfterTheExpression() + { + int maxSize = -1; + + ArgumentOutOfRangeException exception = SystemInfo.CreateArgumentOutOfRangeException(maxSize, "message"); + + Assert.That(exception.ParamName, Is.EqualTo("maxSize")); + Assert.That(exception.ActualValue, Is.EqualTo(-1)); + Assert.That(exception.Message, Does.StartWith("message")); + } + + /// A setter passes value, the name the runtime gives a setter's parameter. + [Test] + public void ASetterNamesTheParameterValue() + => Assert.That(() => new log4net.Appender.TelnetAppender().SendQueueSize = 0, + Throws.TypeOf() + .With.Property(nameof(ArgumentOutOfRangeException.ParamName)).EqualTo("value")); +} diff --git a/src/log4net/Appender/AppenderCollection.cs b/src/log4net/Appender/AppenderCollection.cs index 36357272c..84f37bd90 100644 --- a/src/log4net/Appender/AppenderCollection.cs +++ b/src/log4net/Appender/AppenderCollection.cs @@ -484,17 +484,17 @@ public virtual IAppender[] ToArray() } /// - /// is less than zero + /// is less than zero /// -or- - /// is equal to or greater than . + /// is equal to or greater than . /// - private void ValidateIndex(int i, bool allowEqualEnd = false) + private void ValidateIndex(int index, bool allowEqualEnd = false) { int max = allowEqualEnd ? _count : (_count - 1); - if (i < 0 || i > max) + if (index < 0 || index > max) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(i), i, - $"Index was out of range. Must be non-negative and less than the size of the collection. [{i}] Specified argument was out of the range of valid values."); + throw SystemInfo.CreateArgumentOutOfRangeException(index, + $"Index was out of range. Must be non-negative and less than the size of the collection. [{index}] Specified argument was out of the range of valid values."); } } diff --git a/src/log4net/Appender/FileAppender.cs b/src/log4net/Appender/FileAppender.cs index 1290e03db..71c7783a8 100644 --- a/src/log4net/Appender/FileAppender.cs +++ b/src/log4net/Appender/FileAppender.cs @@ -693,7 +693,7 @@ public int LockTimeoutMillis { if (value < 0 && value != Timeout.Infinite) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified for LockTimeoutMillis is negative and is not {nameof(Timeout)}.{nameof(Timeout.Infinite)}."); } _lockTimeoutMillis = value; diff --git a/src/log4net/Appender/LocalSyslogAppender.cs b/src/log4net/Appender/LocalSyslogAppender.cs index 2f373a827..cc9f3858e 100644 --- a/src/log4net/Appender/LocalSyslogAppender.cs +++ b/src/log4net/Appender/LocalSyslogAppender.cs @@ -303,7 +303,7 @@ public override void ActivateOptions() base.ActivateOptions(); if (NewLineHandling is not (SyslogNewLineHandling.Escape or SyslogNewLineHandling.Keep or SyslogNewLineHandling.Split)) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(NewLineHandling), NewLineHandling, + throw SystemInfo.CreateArgumentOutOfRangeException(NewLineHandling, $"The NewLineHandling is not {SyslogNewLineHandling.Escape} or {SyslogNewLineHandling.Keep} or {SyslogNewLineHandling.Split}."); } @@ -413,7 +413,7 @@ public int MaxRecordSize { if (value < MinRecordSize) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {MinRecordSize}."); } field = value; diff --git a/src/log4net/Appender/RemoteSyslogAppender.cs b/src/log4net/Appender/RemoteSyslogAppender.cs index ac320de62..a4cf2ffde 100644 --- a/src/log4net/Appender/RemoteSyslogAppender.cs +++ b/src/log4net/Appender/RemoteSyslogAppender.cs @@ -509,7 +509,7 @@ public override void ActivateOptions() base.ActivateOptions(); if (NewLineHandling is not (SyslogNewLineHandling.Escape or SyslogNewLineHandling.Keep or SyslogNewLineHandling.Split)) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(NewLineHandling), NewLineHandling, + throw SystemInfo.CreateArgumentOutOfRangeException(NewLineHandling, $"The NewLineHandling is not {SyslogNewLineHandling.Escape} or {SyslogNewLineHandling.Keep} or {SyslogNewLineHandling.Split}."); } _levelMapping.ActivateOptions(); @@ -545,7 +545,7 @@ public int SendQueueSize { if (value <= 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendQueueSize is not positive."); } _sendQueueSize = value; @@ -566,7 +566,7 @@ public int EnqueueTimeoutMillis { if (value < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for EnqueueTimeoutMillis is negative."); } _enqueueTimeoutMillis = value; diff --git a/src/log4net/Appender/RollingFileAppender.cs b/src/log4net/Appender/RollingFileAppender.cs index 783a6170b..178a9c4ec 100644 --- a/src/log4net/Appender/RollingFileAppender.cs +++ b/src/log4net/Appender/RollingFileAppender.cs @@ -1801,7 +1801,7 @@ public int LockTimeoutMillis { if (value < 0 && value != Timeout.Infinite) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified for LockTimeoutMillis is negative and is not {nameof(Timeout)}.{nameof(Timeout.Infinite)}."); } _lockTimeoutMillis = value; diff --git a/src/log4net/Appender/SmtpAppender.cs b/src/log4net/Appender/SmtpAppender.cs index a297da4c4..78ee96610 100644 --- a/src/log4net/Appender/SmtpAppender.cs +++ b/src/log4net/Appender/SmtpAppender.cs @@ -314,7 +314,7 @@ public int MaxBodySize { if (value < MailBodies.MinBodySize) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {MailBodies.MinBodySize}."); } field = value; @@ -371,7 +371,7 @@ public int SendTimeoutMillis { if (value <= 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendTimeoutMillis is not positive."); } _sendTimeoutMillis = value; diff --git a/src/log4net/Appender/TelnetAppender.cs b/src/log4net/Appender/TelnetAppender.cs index 9ae2bfd41..cb7f94309 100644 --- a/src/log4net/Appender/TelnetAppender.cs +++ b/src/log4net/Appender/TelnetAppender.cs @@ -86,7 +86,7 @@ public int SendQueueSize { if (value <= 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendQueueSize is not positive."); } _sendQueueSize = value; @@ -112,7 +112,7 @@ public int EnqueueTimeoutMillis { if (value < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for EnqueueTimeoutMillis is negative."); } _enqueueTimeoutMillis = value; @@ -170,7 +170,7 @@ public int Port { if (value is < IPEndPoint.MinPort or > IPEndPoint.MaxPort) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified for Port is less than {IPEndPoint.MinPort} or greater than {IPEndPoint.MaxPort}."); } _listeningPort = value; @@ -206,7 +206,7 @@ public int SendTimeoutMillis { if (value < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for SendTimeoutMillis is negative."); } _sendTimeoutMillis = value; diff --git a/src/log4net/Appender/UdpAppender.cs b/src/log4net/Appender/UdpAppender.cs index 15d37f664..3e913c938 100644 --- a/src/log4net/Appender/UdpAppender.cs +++ b/src/log4net/Appender/UdpAppender.cs @@ -175,7 +175,7 @@ public int RemotePort { if (value is < IPEndPoint.MinPort or > IPEndPoint.MaxPort) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {IPEndPoint.MinPort} or greater than {IPEndPoint.MaxPort}."); } _remotePort = value; @@ -206,7 +206,7 @@ public int LocalPort { if (value is not 0 and (< IPEndPoint.MinPort or > IPEndPoint.MaxPort)) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {IPEndPoint.MinPort} or greater than {IPEndPoint.MaxPort}."); } _localPort = value; @@ -260,7 +260,7 @@ public int MaxDatagramSize { if (value is < MinDatagramSize or > MaxIPv4DatagramSize) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, $"The value specified is less than {MinDatagramSize} or greater than {MaxIPv4DatagramSize}."); } _maxDatagramSize = value; @@ -321,12 +321,12 @@ public override void ActivateOptions() if (RemotePort is < IPEndPoint.MinPort or > IPEndPoint.MaxPort) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(RemotePort), RemotePort, + throw SystemInfo.CreateArgumentOutOfRangeException(RemotePort, $"The RemotePort is less than {IPEndPoint.MinPort} or greater than {IPEndPoint.MaxPort}."); } if (LocalPort is not 0 and (< IPEndPoint.MinPort or > IPEndPoint.MaxPort)) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(LocalPort), LocalPort, + throw SystemInfo.CreateArgumentOutOfRangeException(LocalPort, $"The LocalPort is less than {IPEndPoint.MinPort} or greater than {IPEndPoint.MaxPort}."); } RemoteEndPoint = new(RemoteAddress, RemotePort); diff --git a/src/log4net/Core/DefaultRepositorySelector.cs b/src/log4net/Core/DefaultRepositorySelector.cs index 406f11529..6d8e5eee4 100644 --- a/src/log4net/Core/DefaultRepositorySelector.cs +++ b/src/log4net/Core/DefaultRepositorySelector.cs @@ -77,7 +77,7 @@ public DefaultRepositorySelector([DynamicallyAccessedMembers(DynamicallyAccessed // Check that the type is a repository if (!typeof(ILoggerRepository).IsAssignableFrom(defaultRepositoryType.EnsureNotNull())) { - throw SystemInfo.CreateArgumentOutOfRangeException("defaultRepositoryType", defaultRepositoryType, + throw SystemInfo.CreateArgumentOutOfRangeException(defaultRepositoryType, $"Parameter: defaultRepositoryType, Value: [{defaultRepositoryType}] out of range. Argument must implement the ILoggerRepository interface"); } diff --git a/src/log4net/Core/LevelCollection.cs b/src/log4net/Core/LevelCollection.cs index e666d2562..d653cce42 100644 --- a/src/log4net/Core/LevelCollection.cs +++ b/src/log4net/Core/LevelCollection.cs @@ -483,24 +483,24 @@ public virtual int AddRange(ICollection collection) public virtual void TrimToSize() => Capacity = Count; /// - /// is less than zero + /// is less than zero /// -or- - /// is equal to or greater than . + /// is equal to or greater than . /// - private void ValidateIndex(int i) => ValidateIndex(i, false); + private void ValidateIndex(int index) => ValidateIndex(index, false); /// - /// is less than zero + /// is less than zero /// -or- - /// is equal to or greater than . + /// is equal to or greater than . /// - private void ValidateIndex(int i, bool allowEqualEnd) + private void ValidateIndex(int index, bool allowEqualEnd) { int max = allowEqualEnd ? Count : (Count - 1); - if (i < 0 || i > max) + if (index < 0 || index > max) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(i), i, - $"Index was out of range. Must be non-negative and less than the size of the collection. [{i}] Specified argument was out of the range of valid values."); + throw SystemInfo.CreateArgumentOutOfRangeException(index, + $"Index was out of range. Must be non-negative and less than the size of the collection. [{index}] Specified argument was out of the range of valid values."); } } diff --git a/src/log4net/Core/LevelMap.cs b/src/log4net/Core/LevelMap.cs index f5d3e5fbb..88b252312 100644 --- a/src/log4net/Core/LevelMap.cs +++ b/src/log4net/Core/LevelMap.cs @@ -85,7 +85,7 @@ public void Add(string name, int value, string? displayName) { if (name.EnsureNotNull().Length == 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(name), name, + throw SystemInfo.CreateArgumentOutOfRangeException(name, $"Parameter: name, Value: [{name}] out of range. Level name must not be empty"); } diff --git a/src/log4net/Filter/StringMatchFilter.cs b/src/log4net/Filter/StringMatchFilter.cs index 676a9e088..f90f6b3f4 100644 --- a/src/log4net/Filter/StringMatchFilter.cs +++ b/src/log4net/Filter/StringMatchFilter.cs @@ -98,7 +98,7 @@ public int MatchTimeoutMillis { if (value < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for MatchTimeoutMillis is negative."); } _matchTimeoutMillis = value; @@ -134,7 +134,7 @@ public FilterDecision TimeoutDecision { if (value is not (FilterDecision.Deny or FilterDecision.Neutral or FilterDecision.Accept)) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(value), value, + throw SystemInfo.CreateArgumentOutOfRangeException(value, "The value specified for TimeoutDecision is not Deny, Neutral or Accept."); } field = value; diff --git a/src/log4net/Plugin/PluginCollection.cs b/src/log4net/Plugin/PluginCollection.cs index b836f9b55..2c4b614e3 100644 --- a/src/log4net/Plugin/PluginCollection.cs +++ b/src/log4net/Plugin/PluginCollection.cs @@ -512,23 +512,23 @@ public virtual int AddRange(ICollection collection) public virtual void TrimToSize() => Capacity = _count; /// - /// is less than zero. + /// is less than zero. /// -or- - /// is equal to or greater than . + /// is equal to or greater than . /// - private void ValidateIndex(int i) => ValidateIndex(i, false); + private void ValidateIndex(int index) => ValidateIndex(index, false); /// - /// is less than zero. + /// is less than zero. /// -or- - /// is equal to or greater than . + /// is equal to or greater than . /// - private void ValidateIndex(int i, bool allowEqualEnd) + private void ValidateIndex(int index, bool allowEqualEnd) { int max = allowEqualEnd ? _count : (_count - 1); - if (i < 0 || i > max) + if (index < 0 || index > max) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(i), i, $"Index was out of range. Must be non-negative and less than the size of the collection. [{i}] Specified argument was out of the range of valid values."); + throw SystemInfo.CreateArgumentOutOfRangeException(index, $"Index was out of range. Must be non-negative and less than the size of the collection. [{index}] Specified argument was out of the range of valid values."); } } diff --git a/src/log4net/Util/CyclicBuffer.cs b/src/log4net/Util/CyclicBuffer.cs index c376d0704..c1d482072 100644 --- a/src/log4net/Util/CyclicBuffer.cs +++ b/src/log4net/Util/CyclicBuffer.cs @@ -52,7 +52,7 @@ public CyclicBuffer(int maxSize) { if (maxSize < 1) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(maxSize), maxSize, $"Parameter: {nameof(maxSize)}, Value: [{maxSize}] out of range. A positive integer is required."); + throw SystemInfo.CreateArgumentOutOfRangeException(maxSize, $"Parameter: {nameof(maxSize)}, Value: [{maxSize}] out of range. A positive integer is required."); } _maxSize = maxSize; @@ -213,7 +213,7 @@ public void Resize(int newSize) { if (newSize < 0) { - throw SystemInfo.CreateArgumentOutOfRangeException(nameof(newSize), newSize, $"Parameter: {nameof(newSize)}, Value: [{newSize}] out of range. A positive integer is required."); + throw SystemInfo.CreateArgumentOutOfRangeException(newSize, $"Parameter: {nameof(newSize)}, Value: [{newSize}] out of range. A positive integer is required."); } if (newSize == numElems) { diff --git a/src/log4net/Util/SystemInfo.cs b/src/log4net/Util/SystemInfo.cs index d121e5949..45fe8d178 100644 --- a/src/log4net/Util/SystemInfo.cs +++ b/src/log4net/Util/SystemInfo.cs @@ -23,6 +23,7 @@ using System.Reflection; using System.IO; using System.Collections; +using System.ComponentModel; using System.Runtime.CompilerServices; namespace log4net.Util; @@ -601,17 +602,18 @@ public static string AssemblyFileName(Assembly myAssembly) } /// - /// Creates an + /// Creates an named after the expression passed as . /// - /// The name of the parameter that caused the exception - /// The value of the argument that causes this exception - /// The message that describes the error - /// - /// A new instance of the class - /// with the specified error message, parameter name, and value - /// of the argument. - /// - public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message) + /// The value of the argument that causes this exception. + /// The message that describes the error. + /// Filled in by the compiler; do not pass it. + /// The exception, for the caller to throw. + /// + /// Public only because log4net.Ext.Mail is not strong named and so cannot be a friend assembly. + /// + [EditorBrowsable(EditorBrowsableState.Never)] + public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(object actualValue, string message, + [CallerArgumentExpression(nameof(actualValue))] string parameterName = "") => new(parameterName, actualValue, message); ///