diff --git a/src/changelog/3.6.1/366-flush-takes-the-file-lock.xml b/src/changelog/3.6.1/366-flush-takes-the-file-lock.xml
new file mode 100644
index 00000000..36e111a7
--- /dev/null
+++ b/src/changelog/3.6.1/366-flush-takes-the-file-lock.xml
@@ -0,0 +1,12 @@
+
+
+
+
+ `FileAppender.Flush(int)` with `ImmediateFlush=false` no longer
+ drops the buffered text and returns `false`: it takes the file lock and writes the text.
+ With `InterProcessLock` and `MinimalLock` nothing is left buffered, as they flush before
+ each release, so it returns immediately (ANT-2026-98BDXCN5, fixed by @FreeAndNil)
+
diff --git a/src/changelog/3.6.1/366-shared-locks-flush-before-release.xml b/src/changelog/3.6.1/366-shared-locks-flush-before-release.xml
new file mode 100644
index 00000000..f262bdb8
--- /dev/null
+++ b/src/changelog/3.6.1/366-shared-locks-flush-before-release.xml
@@ -0,0 +1,14 @@
+
+
+
+
+ `InterProcessLock` and `MinimalLock` write out their buffered text
+ before releasing the lock, so processes sharing a file no longer overwrite or split each other's
+ records: `ImmediateFlush=false` has no effect with them and is reported once per activation. A long
+ header, a layout throwing halfway and the footer no longer leave text behind; the footer is written
+ and the file closed within a single lock
+ (ANT-2026-EAZMFSKC, fixed by @FreeAndNil)
+
diff --git a/src/changelog/3.6.1/367-global-mutex-names.xml b/src/changelog/3.6.1/367-global-mutex-names.xml
new file mode 100644
index 00000000..694efdd3
--- /dev/null
+++ b/src/changelog/3.6.1/367-global-mutex-names.xml
@@ -0,0 +1,11 @@
+
+
+
+
+ Outside Windows `InterProcessLock` and `RollingFileAppender` now lock
+ the file across login sessions, so processes started separately, such as services and cron jobs, no
+ longer write at the same time (fixed by @FreeAndNil)
+
diff --git a/src/changelog/3.6.1/367-minimal-lock-excludes-writers.xml b/src/changelog/3.6.1/367-minimal-lock-excludes-writers.xml
new file mode 100644
index 00000000..f0d1f38f
--- /dev/null
+++ b/src/changelog/3.6.1/367-minimal-lock-excludes-writers.xml
@@ -0,0 +1,11 @@
+
+
+
+
+ Outside Windows `MinimalLock` keeps other writers out while it
+ writes, so one process no longer overwrites the event another just wrote. Readers are not blocked;
+ an event that cannot get the lock within 10 seconds is reported and dropped (ANT-2026-JC5GM7W7, fixed by @FreeAndNil)
+
diff --git a/src/changelog/3.6.1/368-retried-open-suffix-once.xml b/src/changelog/3.6.1/368-retried-open-suffix-once.xml
new file mode 100644
index 00000000..a91254a6
--- /dev/null
+++ b/src/changelog/3.6.1/368-retried-open-suffix-once.xml
@@ -0,0 +1,11 @@
+
+
+
+
+ `RollingFileAppender` with `StaticLogFileName=false` retries a failed
+ open under the right file name; each retry used to add the roll suffix again and leave one more empty
+ file behind (fixed by @FreeAndNil)
+
diff --git a/src/changelog/3.6.1/368-timed-out-open-waits-once.xml b/src/changelog/3.6.1/368-timed-out-open-waits-once.xml
new file mode 100644
index 00000000..a4b017c1
--- /dev/null
+++ b/src/changelog/3.6.1/368-timed-out-open-waits-once.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ After an open of the log file timed out on the lock, each retrying
+ event waits once instead of four times and no longer leaks a file stream. An open retried after a
+ failure appends instead of truncating, whatever the locking model, also with `AppendToFile=false`,
+ so what another process wrote meanwhile stays. `FileAppender.OpenFile` no longer sets
+ `AppendToFile` (ANT-2026-D1OOS5L6, fixed by @FreeAndNil)
+
diff --git a/src/log4net.Tests/Appender/FileAppenderFlushTest.cs b/src/log4net.Tests/Appender/FileAppenderFlushTest.cs
new file mode 100644
index 00000000..4e58e4a9
--- /dev/null
+++ b/src/log4net.Tests/Appender/FileAppenderFlushTest.cs
@@ -0,0 +1,328 @@
+#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.IO;
+using System.Runtime.ExceptionServices;
+using System.Threading;
+
+using log4net.Appender;
+using log4net.Core;
+using log4net.Layout;
+using log4net.Tests.Appender.Internal;
+using log4net.Util;
+
+using NUnit.Framework;
+
+using PeanutButter.Utils;
+
+using static log4net.Tests.Appender.Internal.TestFileAppenders;
+
+namespace log4net.Tests.Appender;
+
+///
+/// writes the buffered text under the file lock.
+///
+[TestFixture]
+public sealed class FileAppenderFlushTest
+{
+ ///
+ /// Flush(int) wrote without the file lock: the locking stream refused, the flush returned
+ /// and the buffered text was lost.
+ ///
+ [TestCase(typeof(FileAppender.NoLock))]
+ [TestCase(typeof(FileAppender.MinimalLock))]
+ [TestCase(typeof(FileAppender.ExclusiveLock))]
+ [TestCase(typeof(FileAppender.InterProcessLock))]
+ public void FlushWritesTheBufferedText(Type lockingModel)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "flushed.log");
+ FileAppender appender = CreateAppender(file, (FileAppender.LockingModelBase)Activator.CreateInstance(lockingModel)!);
+ appender.ImmediateFlush = false;
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+
+ appender.DoAppend(CreateEvent("buffered"));
+ bool isFlushed = appender.Flush(0);
+ string afterFlush = ReadWhileOpen(file);
+ appender.Close();
+
+ Assert.That(isFlushed, Is.True);
+ Assert.That(afterFlush, Is.EqualTo("buffered" + Environment.NewLine));
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty);
+ }
+
+ ///
+ /// Without an open file there is nothing to flush: , nothing reported.
+ ///
+ [TestCase(true)]
+ [TestCase(false)]
+ public void FlushWithoutAnOpenFileHasNothingToDo(bool isClosed)
+ {
+ using AutoTempFolder folder = new();
+ // Not a shared lock: those return before the writer is checked.
+ FileAppender appender = CreateAppender(Path.Combine(folder.Path, "closed.log"), new FileAppender.ExclusiveLock());
+ appender.ImmediateFlush = false;
+ if (isClosed)
+ {
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+ appender.Close();
+ }
+ else
+ {
+ appender.File = null;
+ }
+
+ Assert.That(appender.Flush(0), Is.True);
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty);
+ }
+
+ ///
+ /// A flush during an append waits for it on the appender lock before it touches the file lock.
+ /// The other order raised the lock count of the writer's acquisition and released it on the
+ /// flushing thread.
+ ///
+ [Test]
+ public void FlushTakesTheAppenderLockBeforeTheFileLock()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "ordered.log");
+ using ManualResetEventSlim entered = new();
+ using ManualResetEventSlim gate = new();
+ ThreadCheckingLock lockingModel = new();
+ FileAppender appender = CreateAppender(file, lockingModel);
+ appender.Layout = new GateLayout(entered, gate);
+ appender.ImmediateFlush = false;
+ appender.ActivateOptions();
+ // Warms up, so that JIT or type initialisation cannot pass for a flusher blocked on the lock.
+ appender.Flush(0);
+ lockingModel.Reset();
+ ExceptionDispatchInfo? failure = null;
+ bool isFlushed = false;
+
+ Thread writer = StartWorker(() => appender.DoAppend(CreateEvent("record")), e => failure = e);
+ Thread flusher;
+ bool isParked;
+ try
+ {
+ Assert.That(entered.Wait(TimeSpan.FromSeconds(10)), Is.True, "the writer never reached the layout");
+ flusher = StartWorker(() => isFlushed = appender.Flush(0), e => failure = e);
+ isParked = TryWaitUntilBlocked(flusher);
+ }
+ finally
+ {
+ gate.Set();
+ }
+ Assert.That(writer.Join(TimeSpan.FromSeconds(10)), Is.True, "the writer did not finish");
+ Assert.That(flusher.Join(TimeSpan.FromSeconds(10)), Is.True, "the flusher did not finish");
+ failure?.Throw();
+ (int acquired, int released, int foreignReleases) = (lockingModel.Acquired, lockingModel.Released, lockingModel.ForeignReleases);
+ string afterFlush = ReadWhileOpen(file);
+ appender.Close();
+
+ Assert.That(isParked, Is.True, "the flusher was never seen waiting for the writer");
+ Assert.That(foreignReleases, Is.EqualTo(0));
+ Assert.That(acquired, Is.EqualTo(2));
+ Assert.That(released, Is.EqualTo(2));
+ Assert.That(isFlushed, Is.True);
+ Assert.That(afterFlush, Is.EqualTo("record" + Environment.NewLine));
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty);
+ }
+
+ ///
+ /// A flush that cannot get the file lock reports .
+ ///
+ [Test]
+ public void FlushWithoutTheFileLockFails()
+ {
+ using AutoTempFolder folder = new();
+ ThreadCheckingLock lockingModel = new();
+ FileAppender appender = CreateAppender(Path.Combine(folder.Path, "refused.log"), lockingModel);
+ appender.ImmediateFlush = false;
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("record"));
+
+ lockingModel.IsRefusing = true;
+ bool isFlushed = appender.Flush(0);
+ lockingModel.IsRefusing = false;
+ appender.Close();
+
+ Assert.That(isFlushed, Is.False);
+ }
+
+ ///
+ /// The shared locks leave nothing buffered, so a flush has nothing to wait for, even with the lock held elsewhere.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void FlushWithASharedLockDoesNotWaitForIt()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ CountingInterProcessLock lockingModel = new() { LockTimeoutMillis = 200 };
+ FileAppender appender = CreateAppender(file, lockingModel);
+ appender.ImmediateFlush = false;
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+ appender.DoAppend(CreateEvent("record"));
+ lockingModel.Acquired = 0;
+ bool isFlushed;
+
+ using (new HeldLock(file))
+ {
+ isFlushed = appender.Flush(0);
+ }
+ int acquired = lockingModel.Acquired;
+ appender.Close();
+
+ Assert.That(isFlushed, Is.True);
+ Assert.That(acquired, Is.EqualTo(0));
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty);
+ }
+
+ ///
+ /// likewise: a flush does not take the lock, so it does not open the file.
+ ///
+ [Test]
+ public void FlushWithTheMinimalLockDoesNotTakeIt()
+ {
+ using AutoTempFolder folder = new();
+ CountingMinimalLock lockingModel = new();
+ FileAppender appender = CreateAppender(Path.Combine(folder.Path, "minimal.log"), lockingModel);
+ appender.ImmediateFlush = false;
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+ appender.DoAppend(CreateEvent("record"));
+ lockingModel.Acquired = 0;
+
+ bool isFlushed = appender.Flush(0);
+ int acquired = lockingModel.Acquired;
+ appender.Close();
+
+ Assert.That(isFlushed, Is.True);
+ Assert.That(acquired, Is.EqualTo(0));
+ }
+
+ /// Counts the calls to .
+ private sealed class CountingMinimalLock : FileAppender.MinimalLock
+ {
+ internal int Acquired { get; set; }
+
+ ///
+ public override Stream? AcquireLock()
+ {
+ Acquired++;
+ return base.AcquireLock();
+ }
+ }
+
+ ///
+ /// Waits up to 10 seconds until blocks or ends; whether it blocked.
+ ///
+ private static bool TryWaitUntilBlocked(Thread thread)
+ {
+ const ThreadState blockedOrEnded = ThreadState.WaitSleepJoin | ThreadState.Stopped;
+ SpinWait.SpinUntil(() => (thread.ThreadState & blockedOrEnded) != 0, TimeSpan.FromSeconds(10));
+ return (thread.ThreadState & ThreadState.WaitSleepJoin) != 0;
+ }
+
+ /// Runs on a background thread, handing an exception to .
+ private static Thread StartWorker(Action action, Action onFailure)
+ {
+ Thread thread = new(() =>
+ {
+ try
+ {
+ action();
+ }
+ catch (Exception e) when (!e.IsFatal())
+ {
+ onFailure(ExceptionDispatchInfo.Capture(e));
+ }
+ })
+ { IsBackground = true };
+ thread.Start();
+ return thread;
+ }
+
+ ///
+ /// An exclusive lock that records the acquiring thread and counts releases on any other thread.
+ ///
+ private sealed class ThreadCheckingLock : FileAppender.ExclusiveLock
+ {
+ private int _acquiringThread;
+
+ internal int Acquired { get; private set; }
+
+ internal int Released { get; private set; }
+
+ internal int ForeignReleases { get; private set; }
+
+ internal bool IsRefusing { get; set; }
+
+ internal void Reset() => (Acquired, Released, ForeignReleases) = (0, 0, 0);
+
+ ///
+ public override Stream? AcquireLock()
+ {
+ if (IsRefusing)
+ {
+ return null;
+ }
+ Stream? stream = base.AcquireLock();
+ _acquiringThread = Environment.CurrentManagedThreadId;
+ Acquired++;
+ return stream;
+ }
+
+ ///
+ public override void ReleaseLock()
+ {
+ if (Environment.CurrentManagedThreadId != _acquiringThread)
+ {
+ ForeignReleases++;
+ }
+ Released++;
+ base.ReleaseLock();
+ }
+ }
+
+ /// Parks the first event it formats until the gate opens.
+ private sealed class GateLayout(ManualResetEventSlim entered, ManualResetEventSlim gate) : LayoutSkeleton
+ {
+ private bool _hasParked;
+
+ ///
+ public override void ActivateOptions()
+ { }
+
+ ///
+ public override void Format(TextWriter writer, LoggingEvent loggingEvent)
+ {
+ if (!_hasParked)
+ {
+ _hasParked = true;
+ entered.Set();
+ if (!gate.Wait(TimeSpan.FromSeconds(10)))
+ {
+ throw new TimeoutException("the gate was never opened");
+ }
+ }
+ writer.Write(loggingEvent.RenderedMessage + Environment.NewLine);
+ }
+ }
+}
diff --git a/src/log4net.Tests/Appender/FileAppenderMutexNameTest.cs b/src/log4net.Tests/Appender/FileAppenderMutexNameTest.cs
index e1402789..23d7f7b4 100644
--- a/src/log4net.Tests/Appender/FileAppenderMutexNameTest.cs
+++ b/src/log4net.Tests/Appender/FileAppenderMutexNameTest.cs
@@ -25,6 +25,7 @@
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
+using log4net.Tests.Appender.Internal;
using log4net.Util;
using NUnit.Framework;
@@ -218,6 +219,74 @@ public void ThePlatformDecidesWhetherALongNameIsHashed()
}
}
+ ///
+ /// Outside Windows a plain mutex name is per session, so two services or a service and a cron job
+ /// did not exclude each other: the name is global there.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void TheMutexNameIsGlobalOutsideWindows()
+ {
+ string name = MutexName("/var/log/app.log", "_rolling");
+
+ Assert.That(name, Is.EqualTo(@"Global\_var_log_app.log_rolling"));
+ }
+
+ ///
+ /// The prefix comes on top of a name already at the limit, and the platform still accepts it.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AGlobalNameAtTheLimitCanBeCreated()
+ {
+ string name = MutexName("/" + new string('d', 4000) + "/app.log", "_rolling");
+
+ using Mutex mutex = new(false, name);
+ Assert.That(mutex.WaitOne(0), Is.True);
+ mutex.ReleaseMutex();
+ }
+
+ ///
+ /// The roll lock goes by the same global name: held by another process, the appender writes without
+ /// rolling instead of rolling under it.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void TheRollLockIsTheGlobalOne()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "rolling.log");
+ RollingFileAppender appender = new()
+ {
+ File = file,
+ RollingStyle = RollingFileAppender.RollingMode.Size,
+ MaxFileSize = 1,
+ MaxSizeRollBackups = 1,
+ LockTimeoutMillis = 200,
+ Layout = new PatternLayout("%message%newline"),
+ ErrorHandler = new RecordingErrorHandler()
+ };
+ appender.ActivateOptions();
+
+ using (new HeldLock(file, "_rolling"))
+ {
+ appender.DoAppend(new LoggingEvent(typeof(FileAppenderMutexNameTest), null, "test", Level.Info, "first", null));
+ appender.DoAppend(new LoggingEvent(typeof(FileAppenderMutexNameTest), null, "test", Level.Info, "second", null));
+ }
+ appender.Close();
+
+ Assert.That(Directory.GetFiles(folder.Path), Has.Length.EqualTo(1));
+ }
+
+ /// On Windows the name stays as earlier versions computed it: a global one needs a shared ACL.
+ [Test]
+ [Platform("Win")]
+ public void TheMutexNameIsUnprefixedOnWindows()
+ => Assert.That(MutexName("/var/log/app.log", "_rolling"), Is.EqualTo("_var_log_app.log_rolling"));
+
+ private static string MutexName(string path, string suffix)
+ => typeof(FileAppender).Invoke(nameof(MutexName), [path, suffix]);
+
private static string MutexNameForPath(string path, string suffix)
=> typeof(FileAppender).Invoke(nameof(MutexNameForPath), [path, suffix]);
diff --git a/src/log4net.Tests/Appender/FileAppenderTest.cs b/src/log4net.Tests/Appender/FileAppenderTest.cs
index ab6f3a5b..e62fa893 100644
--- a/src/log4net.Tests/Appender/FileAppenderTest.cs
+++ b/src/log4net.Tests/Appender/FileAppenderTest.cs
@@ -20,6 +20,7 @@
#endregion
using System.Xml;
+using System.Collections.Generic;
using System;
using log4net.Appender;
using NUnit.Framework;
@@ -36,6 +37,9 @@
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
+using log4net.Tests.Appender.Internal;
+
+using static log4net.Tests.Appender.Internal.TestFileAppenders;
namespace log4net.Tests.Appender;
@@ -75,8 +79,8 @@ private static void Reset()
[Test]
public void FilenameWithPatternStringTest()
{
- LogLog.LogReceived += LogReceived;
- try
+ List messages = [];
+ using (new LogLog.LogReceivedAdapter(messages))
{
XmlDocument log4NetConfig = new();
log4NetConfig.LoadXml(
@@ -104,12 +108,8 @@ public void FilenameWithPatternStringTest()
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
XmlConfigurator.Configure(rep, log4NetConfig["log4net"]!);
}
- finally
- {
- LogLog.LogReceived -= LogReceived;
- }
- static void LogReceived(object? source, LogReceivedEventArgs e) => Assert.Fail(e.LogLog.Message);
+ Assert.That(messages.ConvertAll(m => m.Message), Is.Empty);
}
///
@@ -219,16 +219,498 @@ public void BatchTakesTheInterProcessLockOnce()
Assert.That(acquired, Is.EqualTo(1));
}
- /// Counts the calls to .
- private sealed class CountingInterProcessLock : FileAppender.InterProcessLock
+ ///
+ /// An open that times out on the lock is retried with every event. Each attempt waits once, for
+ /// the open; footer, close and header have no writer to lock for.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void AnOpenThatTimesOutWaitsOnceForTheLock()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ CountingInterProcessLock lockingModel = new() { LockTimeoutMillis = 200 };
+ FileAppender appender = CreateAppender(file, lockingModel);
+ int activation, perEvent, close;
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ activation = lockingModel.Acquired;
+ lockingModel.Acquired = 0;
+ appender.DoAppend(CreateEvent("lost"));
+ perEvent = lockingModel.Acquired;
+ lockingModel.Acquired = 0;
+ appender.Close();
+ close = lockingModel.Acquired;
+ }
+
+ Assert.That(activation, Is.EqualTo(1));
+ Assert.That(perEvent, Is.EqualTo(1));
+ Assert.That(close, Is.EqualTo(0));
+ }
+
+ ///
+ /// Each retried open used to leave the stream of the failed one open until garbage collection.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void ARetriedOpenClosesTheStreamOfTheFailedOne()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ CountingInterProcessLock lockingModel = new() { LockTimeoutMillis = 200 };
+ FileAppender appender = CreateAppender(file, lockingModel);
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("lost"));
+ appender.DoAppend(CreateEvent("lost"));
+ appender.Close();
+ }
+
+ Assert.That(lockingModel.Opened, Is.EqualTo(3));
+ Assert.That(lockingModel.Closed, Is.EqualTo(3));
+ }
+
+ ///
+ /// Once the lock is free again the next event opens the file, header first.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void AnOpenRecoversWithTheHeaderOnceTheLockIsFree()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ FileAppender appender = CreateAppender(file, new FileAppender.InterProcessLock { LockTimeoutMillis = 200 });
+ ((PatternLayout)appender.Layout!).Header = "header" + Environment.NewLine;
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("lost"));
+ }
+ appender.DoAppend(CreateEvent("written"));
+ appender.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("header" + Environment.NewLine + "written" + Environment.NewLine));
+ }
+
+ ///
+ /// With AppendToFile=false only the first open of an activation truncates: a retry used to
+ /// truncate again and drop what the lock holder wrote meanwhile. A new activation truncates again.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void ARetriedOpenAppendsToWhatTheLockHolderWrote()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ File.WriteAllText(file, "old" + Environment.NewLine);
+ FileAppender appender = CreateAppender(file, new FileAppender.InterProcessLock { LockTimeoutMillis = 200 });
+ appender.AppendToFile = false;
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ // The lock holder writes while it holds the lock.
+ using FileStream holder = new(file, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
+ byte[] theirs = Encoding.ASCII.GetBytes("theirs" + Environment.NewLine);
+ holder.Write(theirs, 0, theirs.Length);
+ }
+ appender.DoAppend(CreateEvent("mine"));
+ string afterRetry = ReadWhileOpen(file);
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("again"));
+ appender.Close();
+
+ Assert.That(afterRetry, Is.EqualTo("theirs" + Environment.NewLine + "mine" + Environment.NewLine));
+ Assert.That(File.ReadAllText(file), Is.EqualTo("again" + Environment.NewLine));
+ Assert.That(appender.AppendToFile, Is.False);
+ }
+
+ ///
+ /// A roll closes the writer before it opens the next file; the open's reset takes no lock for the
+ /// writer closed already: footer and close of the old file together, open, header and event take
+ /// one each.
+ ///
+ [Test]
+ public void AnEventThatRollsTakesNoLockForTheClosedWriter()
+ {
+ using AutoTempFolder folder = new();
+ CountingInterProcessLock lockingModel = new();
+ RollingFileAppender appender = new()
+ {
+ File = Path.Combine(folder.Path, "rolling.log"),
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = lockingModel,
+ RollingStyle = RollingFileAppender.RollingMode.Size,
+ MaxFileSize = 1,
+ MaxSizeRollBackups = 2,
+ ErrorHandler = new RecordingErrorHandler()
+ };
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("first"));
+ lockingModel.Acquired = 0;
+
+ appender.DoAppend(CreateEvent("rolls"));
+ int acquired = lockingModel.Acquired;
+ appender.Close();
+
+ Assert.That(acquired, Is.EqualTo(4));
+ }
+
+ ///
+ /// A retry appends, but a roll after it still starts its new file empty with AppendToFile=false.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void ARollAfterARecoveredOpenStartsAnEmptyFile()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "rolling.log");
+ RollingFileAppender appender = new()
+ {
+ File = file,
+ AppendToFile = false,
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = new FileAppender.InterProcessLock { LockTimeoutMillis = 200 },
+ RollingStyle = RollingFileAppender.RollingMode.Size,
+ MaxFileSize = 1,
+ // No backups: the roll truncates in place, so a roll that appended would keep "recovered".
+ MaxSizeRollBackups = 0,
+ ErrorHandler = new RecordingErrorHandler()
+ };
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ }
+ appender.DoAppend(CreateEvent("recovered"));
+ appender.DoAppend(CreateEvent("rolled"));
+ appender.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("rolled" + Environment.NewLine));
+ }
+
+ ///
+ /// Two writers on one file under a shared lock with ImmediateFlush=false: text buffered
+ /// past the lock used to land over, or after, the other writer's records. Each record is longer
+ /// than the writer's 1024 character buffer.
+ ///
+ [TestCase(true, true)]
+ [TestCase(false, true)]
+ [TestCase(true, false)]
+ [TestCase(false, false)]
+ public void SharedLockWritersKeepEachOthersRecordsWhole(bool isMinimalLock, bool isBatch)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "shared.log");
+ FileAppender first = CreateSharedAppender(file, isMinimalLock);
+ FileAppender second = CreateSharedAppender(file, isMinimalLock);
+ string[] records = ["a", "b", "c", "d"];
+
+ for (int i = 0; i < records.Length; i++)
+ {
+ LoggingEvent loggingEvent = CreateEvent(new string(records[i][0], 1100));
+ FileAppender writer = i % 2 == 0 ? first : second;
+ if (isBatch)
+ {
+ writer.DoAppend([loggingEvent]);
+ }
+ else
+ {
+ writer.DoAppend(loggingEvent);
+ }
+ }
+ first.Close();
+ second.Close();
+
+ Assert.That(File.ReadAllText(file),
+ Is.EqualTo(string.Concat(records.Select(r => new string(r[0], 1100) + Environment.NewLine))));
+ }
+
+ ///
+ /// The same for , which inherits the appends.
+ ///
+ [TestCase(true)]
+ [TestCase(false)]
+ public void SharedLockRollingWritersKeepEachOthersRecordsWhole(bool isBatch)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "shared.log");
+ RollingFileAppender[] writers = [CreateSharedRollingAppender(file), CreateSharedRollingAppender(file)];
+ void Append(RollingFileAppender writer, char letter)
+ {
+ LoggingEvent loggingEvent = CreateEvent(new string(letter, 1100));
+ if (isBatch)
+ {
+ writer.DoAppend([loggingEvent]);
+ }
+ else
+ {
+ writer.DoAppend(loggingEvent);
+ }
+ }
+
+ Append(writers[0], 'a');
+ Append(writers[1], 'b');
+ Append(writers[0], 'c');
+ writers[0].Close();
+ writers[1].Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo(new string('a', 1100) + Environment.NewLine
+ + new string('b', 1100) + Environment.NewLine + new string('c', 1100) + Environment.NewLine));
+ }
+
+ ///
+ /// A header longer than the writer's buffer, also with ImmediateFlush=true, used to be
+ /// written after the lock was released, over the other writer's records.
+ ///
+ [Test]
+ public void ALongHeaderDoesNotOverwriteTheOtherWriter()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "shared.log");
+ FileAppender first = CreateAppender(file, new FileAppender.InterProcessLock());
+ first.ActivateOptions();
+ first.DoAppend(CreateEvent("first"));
+ string header = new string('h', 1100) + Environment.NewLine;
+ FileAppender second = CreateAppender(file, new FileAppender.InterProcessLock());
+ ((PatternLayout)second.Layout!).Header = header;
+ second.ActivateOptions();
+ first.DoAppend(CreateEvent("again"));
+ second.DoAppend(CreateEvent("second"));
+ first.Close();
+ second.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("first" + Environment.NewLine + header
+ + "again" + Environment.NewLine + "second" + Environment.NewLine));
+ }
+
+ ///
+ /// A footer longer than the writer's buffer is written and closed under one lock, so the other
+ /// writer's records survive.
+ ///
+ [TestCase(true)]
+ [TestCase(false)]
+ public void ALongFooterDoesNotOverwriteTheOtherWriter(bool isMinimalLock)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "shared.log");
+ string footer = new string('f', 1100) + Environment.NewLine;
+ FileAppender first = CreateSharedAppender(file, isMinimalLock, footer);
+ FileAppender second = CreateSharedAppender(file, isMinimalLock);
+
+ first.DoAppend(CreateEvent("first"));
+ second.DoAppend(CreateEvent("second"));
+ first.Close();
+ second.DoAppend(CreateEvent("again"));
+ second.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("first" + Environment.NewLine + "second" + Environment.NewLine
+ + footer + "again" + Environment.NewLine));
+ }
+
+ ///
+ /// A layout that throws after writing more than the writer's buffer used to leave its text behind,
+ /// to be written later at a stale offset over the other writer's records.
+ ///
+ [TestCase(true)]
+ [TestCase(false)]
+ public void ALayoutThrowingHalfwayDoesNotOverwriteTheOtherWriter(bool isImmediateFlush)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "shared.log");
+ FileAppender first = CreateAppender(file, new FileAppender.InterProcessLock());
+ first.Layout = new ThrowingOnceLayout();
+ first.ImmediateFlush = isImmediateFlush;
+ first.ActivateOptions();
+ FileAppender second = CreateAppender(file, new FileAppender.InterProcessLock());
+ second.ActivateOptions();
+
+ first.DoAppend(CreateEvent("broken"));
+ second.DoAppend(CreateEvent("second"));
+ first.DoAppend(CreateEvent("first"));
+ first.Close();
+ second.Close();
+
+ // The broken record is cut and glued to the next one, but nothing is overwritten.
+ Assert.That(File.ReadAllText(file), Is.EqualTo(new string('x', 1500) + "second" + Environment.NewLine
+ + "first" + Environment.NewLine));
+ }
+
+ ///
+ /// Footer and close take the lock once; a nested attempt inside them does not take it again.
+ ///
+ [Test]
+ public void CloseTakesTheLockOnce()
+ {
+ using AutoTempFolder folder = new();
+ CountingInterProcessLock lockingModel = new();
+ FileAppender appender = CreateAppender(Path.Combine(folder.Path, "close.log"), lockingModel);
+ ((PatternLayout)appender.Layout!).Footer = "footer";
+ appender.ActivateOptions();
+ lockingModel.Acquired = 0;
+
+ appender.Close();
+
+ Assert.That(lockingModel.Acquired, Is.EqualTo(1));
+ }
+
+ ///
+ /// A lock that cannot be had at close is reported, not thrown, and waited for once, not again for
+ /// footer and close; the file is still closed.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void CloseWithTheLockHeldDoesNotThrow()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ CountingInterProcessLock lockingModel = new() { LockTimeoutMillis = 200 };
+ FileAppender appender = CreateAppender(file, lockingModel);
+ appender.ActivateOptions();
+ lockingModel.Acquired = 0;
+
+ using (new HeldLock(file))
+ {
+ Assert.DoesNotThrow(appender.Close);
+ }
+
+ Assert.That(lockingModel.Acquired, Is.EqualTo(1));
+ Assert.That(lockingModel.Closed, Is.EqualTo(lockingModel.Opened));
+ }
+
+ ///
+ /// ImmediateFlush=false has no effect with the shared locks, and says so once per activation.
+ ///
+ [TestCase(typeof(FileAppender.MinimalLock), 1)]
+ [TestCase(typeof(FileAppender.ExclusiveLock), 0)]
+ [TestCase(typeof(FileAppender.InterProcessLock), 1)]
+ public void ImmediateFlushFalseIsReportedAsIgnored(Type lockingModel, int warnings)
+ {
+ using AutoTempFolder folder = new();
+ FileAppender appender = CreateAppender(Path.Combine(folder.Path, "warned.log"),
+ (FileAppender.LockingModelBase)Activator.CreateInstance(lockingModel)!);
+ appender.ImmediateFlush = false;
+ List messages = [];
+
+ LogLog.ExecuteWithoutEmittingInternalMessages(() =>
+ {
+ using LogLog.LogReceivedAdapter _ = new(messages);
+ appender.ActivateOptions();
+ });
+ appender.Close();
+
+ Assert.That(messages.FindAll(m => m.Message.IndexOf("ImmediateFlush=false is ignored", StringComparison.Ordinal) >= 0), Has.Count.EqualTo(warnings));
+ }
+
+ ///
+ /// Control: still buffers with ImmediateFlush=false.
+ ///
+ [Test]
+ public void TheExclusiveLockStillBuffers()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "buffered.log");
+ FileAppender appender = CreateAppender(file, new FileAppender.ExclusiveLock());
+ appender.ImmediateFlush = false;
+ appender.ActivateOptions();
+
+ appender.DoAppend(CreateEvent("buffered"));
+ string beforeClose = ReadWhileOpen(file);
+ appender.Close();
+
+ Assert.That(beforeClose, Is.Empty);
+ Assert.That(File.ReadAllText(file), Is.EqualTo("buffered" + Environment.NewLine));
+ }
+
+ private static FileAppender CreateSharedAppender(string file, bool isMinimalLock, string? footer = null)
+ {
+ FileAppender appender = CreateAppender(file,
+ isMinimalLock ? new FileAppender.MinimalLock() : new FileAppender.InterProcessLock());
+ appender.ImmediateFlush = false;
+ ((PatternLayout)appender.Layout!).Footer = footer;
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+ return appender;
+ }
+
+ private static RollingFileAppender CreateSharedRollingAppender(string file)
+ {
+ RollingFileAppender appender = new()
+ {
+ File = file,
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = new FileAppender.InterProcessLock(),
+ ImmediateFlush = false,
+ ErrorHandler = new RecordingErrorHandler()
+ };
+ LogLog.ExecuteWithoutEmittingInternalMessages(appender.ActivateOptions);
+ return appender;
+ }
+
+ /// Writes 1500 characters and then throws, the first time only.
+ private sealed class ThrowingOnceLayout : LayoutSkeleton
+ {
+ private bool _hasThrown;
+
+ ///
+ public override void ActivateOptions()
+ { }
+
+ ///
+ public override void Format(TextWriter writer, LoggingEvent loggingEvent)
+ {
+ if (!_hasThrown)
+ {
+ _hasThrown = true;
+ writer.Write(new string('x', 1500));
+ throw new InvalidOperationException("rendering failed");
+ }
+ writer.Write(loggingEvent.RenderedMessage + Environment.NewLine);
+ }
+ }
+
+ ///
+ /// Without an open writer close takes no lock, but a subclass overriding CloseWriter is still called.
+ ///
+ [Test]
+ [NonParallelizable]
+ public void CloseAfterAFailedOpenStillCallsTheSubclass()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "held.log");
+ CountingCloseAppender appender = new()
+ {
+ File = file,
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = new FileAppender.InterProcessLock { LockTimeoutMillis = 200 },
+ ErrorHandler = new RecordingErrorHandler()
+ };
+ int closes;
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ closes = appender.Closes;
+ appender.Close();
+ }
+
+ Assert.That(appender.Closes, Is.EqualTo(closes + 1));
+ }
+
+ /// Counts the calls to .
+ private sealed class CountingCloseAppender : FileAppender
{
- internal int Acquired { get; set; }
+ internal int Closes { get; private set; }
///
- public override Stream? AcquireLock()
+ protected override void CloseWriter()
{
- Acquired++;
- return base.AcquireLock();
+ Closes++;
+ base.CloseWriter();
}
}
@@ -283,7 +765,7 @@ public void AcquireLockGivesUpWhenTheLockIsHeldTooLong()
// A mutex has to be taken and released on one thread, so the holder does both.
Task holder = Task.Run(() =>
{
- using Mutex contender = new(false, appenderFile);
+ using Mutex contender = new(false, typeof(FileAppender).Invoke("MutexName", [appenderFile, string.Empty]));
contender.WaitOne();
held.Set();
release.Wait();
diff --git a/src/log4net.Tests/Appender/Internal/CountingInterProcessLock.cs b/src/log4net.Tests/Appender/Internal/CountingInterProcessLock.cs
new file mode 100644
index 00000000..49d1958c
--- /dev/null
+++ b/src/log4net.Tests/Appender/Internal/CountingInterProcessLock.cs
@@ -0,0 +1,56 @@
+#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.IO;
+using System.Text;
+
+using log4net.Appender;
+
+namespace log4net.Tests.Appender.Internal;
+
+/// Counts the calls to , and the files opened and closed.
+internal sealed class CountingInterProcessLock : FileAppender.InterProcessLock
+{
+ internal int Acquired { get; set; }
+
+ internal int Opened { get; private set; }
+
+ internal int Closed { get; private set; }
+
+ ///
+ public override Stream? AcquireLock()
+ {
+ Acquired++;
+ return base.AcquireLock();
+ }
+
+ ///
+ public override void OpenFile(string filename, bool append, Encoding encoding)
+ {
+ Opened++;
+ base.OpenFile(filename, append, encoding);
+ }
+
+ ///
+ public override void CloseFile()
+ {
+ Closed++;
+ base.CloseFile();
+ }
+}
diff --git a/src/log4net.Tests/Appender/Internal/HeldLock.cs b/src/log4net.Tests/Appender/Internal/HeldLock.cs
new file mode 100644
index 00000000..77655de4
--- /dev/null
+++ b/src/log4net.Tests/Appender/Internal/HeldLock.cs
@@ -0,0 +1,65 @@
+#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.Threading;
+using System.Threading.Tasks;
+
+using log4net.Appender;
+
+namespace log4net.Tests.Appender.Internal;
+
+///
+/// Holds the inter process lock of a file on another thread, as another process would, until disposed;
+/// with the suffix _rolling the lock of its roll.
+///
+internal sealed class HeldLock : IDisposable
+{
+ private readonly ManualResetEventSlim _held = new();
+ private readonly ManualResetEventSlim _release = new();
+ private readonly Task _holder;
+
+ internal HeldLock(string file, string suffix = "")
+ {
+ // A mutex has to be taken and released on one thread, so the holder does both.
+ _holder = Task.Run(() =>
+ {
+ using Mutex mutex = new(false, typeof(FileAppender).Invoke("MutexName", [file, suffix]));
+ mutex.WaitOne();
+ _held.Set();
+ _release.Wait();
+ mutex.ReleaseMutex();
+ });
+ if (!_held.Wait(TimeSpan.FromSeconds(10)))
+ {
+ // Lets the holder end in case it takes the mutex after all.
+ _release.Set();
+ throw new TimeoutException("the holder never took the mutex");
+ }
+ }
+
+ ///
+ public void Dispose()
+ {
+ _release.Set();
+ _holder.Wait(TimeSpan.FromSeconds(10));
+ _held.Dispose();
+ _release.Dispose();
+ }
+}
diff --git a/src/log4net.Tests/Appender/Internal/TestFileAppenders.cs b/src/log4net.Tests/Appender/Internal/TestFileAppenders.cs
new file mode 100644
index 00000000..3803fe88
--- /dev/null
+++ b/src/log4net.Tests/Appender/Internal/TestFileAppenders.cs
@@ -0,0 +1,49 @@
+#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.IO;
+
+using log4net.Appender;
+using log4net.Core;
+using log4net.Layout;
+
+namespace log4net.Tests.Appender.Internal;
+
+/// Builds file appenders and events for the file appender tests.
+internal static class TestFileAppenders
+{
+ internal static FileAppender CreateAppender(string file, FileAppender.LockingModelBase lockingModel) => new()
+ {
+ File = file,
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = lockingModel,
+ ErrorHandler = new RecordingErrorHandler()
+ };
+
+ /// Reads a file the appender still holds open, which Windows refuses without shared write access.
+ internal static string ReadWhileOpen(string file)
+ {
+ using FileStream stream = new(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ using StreamReader reader = new(stream);
+ return reader.ReadToEnd();
+ }
+
+ internal static LoggingEvent CreateEvent(string message)
+ => new(typeof(TestFileAppenders), null, "test", Level.Info, message, null);
+}
diff --git a/src/log4net.Tests/Appender/LockingStreamTest.cs b/src/log4net.Tests/Appender/LockingStreamTest.cs
index 9ab732f5..cb034720 100644
--- a/src/log4net.Tests/Appender/LockingStreamTest.cs
+++ b/src/log4net.Tests/Appender/LockingStreamTest.cs
@@ -36,10 +36,13 @@ private sealed class SwitchableLock : FileAppender.LockingModelBase
{
internal bool CanAcquire { get; set; }
+ internal bool IsAcquireThrowing { get; set; }
+
internal int ReleaseCount { get; private set; }
///
- public override Stream? AcquireLock() => CanAcquire ? Stream.Null : null;
+ public override Stream? AcquireLock()
+ => IsAcquireThrowing ? throw new IOException("acquire failed") : CanAcquire ? Stream.Null : null;
///
public override void ReleaseLock() => ReleaseCount++;
@@ -124,6 +127,23 @@ public void RunWithBestEffortLockRunsTheWorkButReleasesOnlyWhatItTook()
}
+ ///
+ /// An acquire that throws must not leave the next call running unlocked without trying.
+ ///
+ [Test]
+ public void RunWithBestEffortLockTriesAgainAfterAnAcquireThatThrew()
+ {
+ SwitchableLock model = new() { CanAcquire = true, IsAcquireThrowing = true };
+ FileAppender appender = new();
+ SetStream(appender, NewLockingStream(model));
+
+ Assert.That(() => RunWithBestEffortLock(appender, () => { }), Throws.Exception);
+ model.IsAcquireThrowing = false;
+ RunWithBestEffortLock(appender, () => { });
+
+ Assert.That(model.ReleaseCount, Is.EqualTo(1));
+ }
+
private static void SetStream(FileAppender appender, object stream)
=> appender.SetFieldValue("_stream", stream);
diff --git a/src/log4net.Tests/Appender/MinimalLockMutexTest.cs b/src/log4net.Tests/Appender/MinimalLockMutexTest.cs
new file mode 100644
index 00000000..63928244
--- /dev/null
+++ b/src/log4net.Tests/Appender/MinimalLockMutexTest.cs
@@ -0,0 +1,241 @@
+#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.IO;
+using System.Threading;
+
+using log4net.Appender;
+using log4net.Layout;
+using log4net.Tests.Appender.Internal;
+using log4net.Util;
+
+using NUnit.Framework;
+
+using PeanutButter.Utils;
+
+using static log4net.Tests.Appender.Internal.TestFileAppenders;
+
+namespace log4net.Tests.Appender;
+
+///
+/// Outside Windows writers take turns through the mutex
+/// uses: a shared open let a second writer in there,
+/// and its write replaced the first one's.
+///
+[TestFixture]
+[NonParallelizable]
+public sealed class MinimalLockMutexTest
+{
+ ///
+ /// A writer that cannot get the mutex in time drops the event and reports it; once the mutex is
+ /// free it writes, and it releases the mutex after each write.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AHeldMutexKeepsTheWriterOut()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "minimal.log");
+ FileAppender appender = CreateMinimalLockAppender(file);
+
+ using (new HeldLock(file))
+ {
+ appender.DoAppend(CreateEvent("lost"));
+ }
+ appender.DoAppend(CreateEvent("written"));
+ // Throws when the writer kept the mutex.
+ using (new HeldLock(file))
+ { }
+ appender.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("written" + Environment.NewLine));
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Has.Count.EqualTo(1));
+ }
+
+ ///
+ /// Control: a reader holding the file open does not keep the writer out.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AReaderDoesNotHoldUpTheWriter()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "minimal.log");
+ FileAppender appender = CreateMinimalLockAppender(file);
+ File.WriteAllText(file, string.Empty);
+
+ string afterAppend;
+ using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
+ {
+ appender.DoAppend(CreateEvent("written"));
+ afterAppend = ReadWhileOpen(file);
+ }
+ appender.Close();
+
+ Assert.That(afterAppend, Is.EqualTo("written" + Environment.NewLine));
+ }
+
+ ///
+ /// An open that fails after the mutex was taken releases it, as no release follows a failed acquire.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AFailedOpenReleasesTheMutex()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "minimal.log");
+ FileAppender appender = CreateMinimalLockAppender(file);
+ File.WriteAllText(file, string.Empty);
+
+ using (new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))
+ {
+ appender.DoAppend(CreateEvent("lost"));
+ }
+ // Throws when the failed open kept the mutex.
+ Assert.DoesNotThrow(() => new HeldLock(file).Dispose());
+ appender.Close();
+ }
+
+ ///
+ /// Without a writable home the runtime cannot create the mutex: one warning, and the writer goes on without it.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AMutexThatCannotBeCreatedIsReportedOnce()
+ {
+ List messages = [];
+ Mutex? mutex = null;
+
+ LogLog.ExecuteWithoutEmittingInternalMessages(() =>
+ {
+ using LogLog.LogReceivedAdapter _ = new(messages);
+ // A name the runtime refuses with the same IOException.
+ mutex = typeof(FileAppender.MinimalLock).Invoke("TryCreateMutex", ["Global\\no/such"]);
+ });
+
+ Assert.That(mutex, Is.Null);
+ Assert.That(messages, Has.Count.EqualTo(1));
+ }
+
+ ///
+ /// A mutex whose owner ended without releasing it counts as taken: the event is written, nothing reported.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void AnAbandonedMutexCountsAsTaken()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "minimal.log");
+ FileAppender appender = CreateMinimalLockAppender(file);
+ using Mutex abandoned = new(false, typeof(FileAppender).Invoke("MutexName", [file, string.Empty]));
+ Thread owner = new(() => abandoned.WaitOne());
+ owner.Start();
+ Assert.That(owner.Join(TimeSpan.FromSeconds(10)), Is.True, "the owner did not end");
+
+ appender.DoAppend(CreateEvent("written"));
+ appender.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("written" + Environment.NewLine));
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty);
+ }
+
+ ///
+ /// Windows refuses a second writer's open already, so there the mutex is not taken.
+ ///
+ [Test]
+ [Platform("Win")]
+ public void WindowsTakesNoMutex()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "minimal.log");
+ FileAppender appender = CreateMinimalLockAppender(file);
+
+ using (new HeldLock(file))
+ {
+ appender.DoAppend(CreateEvent("written"));
+ }
+ appender.Close();
+
+ Assert.That(File.ReadAllText(file), Is.EqualTo("written" + Environment.NewLine));
+ }
+
+ ///
+ /// A rolling appender with a changing file name takes the mutex of its base name, as does.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void ARollingAppenderTakesTheMutexOfItsBaseName()
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "rolling.log");
+ FileAppender.MinimalLock lockingModel = new();
+ lockingModel.Invoke("set_MutexTimeoutMillis", 200);
+ RollingFileAppender appender = new()
+ {
+ File = file,
+ StaticLogFileName = false,
+ RollingStyle = RollingFileAppender.RollingMode.Size,
+ CountDirection = 1,
+ LockingModel = lockingModel,
+ Layout = new PatternLayout("%message%newline"),
+ ErrorHandler = new RecordingErrorHandler()
+ };
+ appender.ActivateOptions();
+
+ using (new HeldLock(file))
+ {
+ appender.DoAppend(CreateEvent("lost"));
+ }
+ appender.Close();
+
+ Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Has.Count.EqualTo(1));
+ }
+
+ ///
+ /// Without a file name there is no mutex, and closing disposes the one there was.
+ ///
+ [Test]
+ [Platform(Exclude = "Win")]
+ public void TheMutexLivesFromActivationToClose()
+ {
+ using AutoTempFolder folder = new();
+ FileAppender.MinimalLock unnamed = new() { CurrentAppender = new FileAppender() };
+ unnamed.ActivateOptions();
+ FileAppender appender = CreateMinimalLockAppender(Path.Combine(folder.Path, "minimal.log"));
+ FileAppender.MinimalLock lockingModel = (FileAppender.MinimalLock)appender.LockingModel;
+ Mutex? whileOpen = lockingModel.GetFieldValue("_mutex");
+
+ appender.Close();
+
+ Assert.That(unnamed.GetFieldValue("_mutex"), Is.Null);
+ Assert.That(whileOpen, Is.Not.Null);
+ Assert.That(lockingModel.GetFieldValue("_mutex"), Is.Null);
+ }
+
+ private static FileAppender CreateMinimalLockAppender(string file)
+ {
+ FileAppender.MinimalLock lockingModel = new();
+ lockingModel.Invoke("set_MutexTimeoutMillis", 200);
+ FileAppender appender = CreateAppender(file, lockingModel);
+ appender.ActivateOptions();
+ return appender;
+ }
+}
diff --git a/src/log4net.Tests/Appender/RollingFileAppenderRetryTest.cs b/src/log4net.Tests/Appender/RollingFileAppenderRetryTest.cs
new file mode 100644
index 00000000..1657f048
--- /dev/null
+++ b/src/log4net.Tests/Appender/RollingFileAppenderRetryTest.cs
@@ -0,0 +1,82 @@
+#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.IO;
+using System.Linq;
+using System.Text;
+
+using log4net.Appender;
+using log4net.Layout;
+using log4net.Tests.Appender.Internal;
+
+using NUnit.Framework;
+
+using PeanutButter.Utils;
+
+using static log4net.Tests.Appender.Internal.TestFileAppenders;
+
+namespace log4net.Tests.Appender;
+
+///
+/// A retrying a failed open adds the roll suffix once.
+///
+[TestFixture]
+public sealed class RollingFileAppenderRetryTest
+{
+ ///
+ /// The retry reopened the suffixed name of the failed open and suffixed it again: one more empty
+ /// file per dropped event. It appends to what the lock holder wrote meanwhile.
+ ///
+ [TestCase(RollingFileAppender.RollingMode.Date)]
+ [TestCase(RollingFileAppender.RollingMode.Size)]
+ [TestCase(RollingFileAppender.RollingMode.Composite)]
+ [NonParallelizable]
+ public void ARetriedOpenAddsTheSuffixOnce(RollingFileAppender.RollingMode rollingStyle)
+ {
+ using AutoTempFolder folder = new();
+ string file = Path.Combine(folder.Path, "rolling.log");
+ RollingFileAppender appender = new()
+ {
+ File = file,
+ StaticLogFileName = false,
+ RollingStyle = rollingStyle,
+ CountDirection = 1,
+ Layout = new PatternLayout("%message%newline"),
+ LockingModel = new FileAppender.InterProcessLock { LockTimeoutMillis = 200 },
+ ErrorHandler = new RecordingErrorHandler()
+ };
+
+ using (new HeldLock(file))
+ {
+ appender.ActivateOptions();
+ appender.DoAppend(CreateEvent("lost"));
+ using FileStream holder = new(Directory.GetFiles(folder.Path).Single(), FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
+ byte[] theirs = Encoding.ASCII.GetBytes("theirs" + Environment.NewLine);
+ holder.Write(theirs, 0, theirs.Length);
+ }
+ appender.DoAppend(CreateEvent("written"));
+ appender.Close();
+
+ string[] files = Directory.GetFiles(folder.Path);
+ Assert.That(files, Has.Length.EqualTo(1), string.Join(", ", files.Select(Path.GetFileName)));
+ Assert.That(File.ReadAllText(files[0]),
+ Is.EqualTo("theirs" + Environment.NewLine + "written" + Environment.NewLine));
+ }
+}
diff --git a/src/log4net.Tests/Appender/RollingFileAppenderTest.cs b/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
index 588436c9..c551bcc5 100644
--- a/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
+++ b/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
@@ -1332,7 +1332,8 @@ public void TestExclusiveLockRecovers()
log.Log(GetType(), Level.Info, "This is a message 2", null);
DestroyLogger();
- AssertFileEquals(filename, "This is a message 2" + Environment.NewLine);
+ // The retry appends to what the lock holder wrote.
+ AssertFileEquals(filename, "Test" + "This is a message 2" + Environment.NewLine);
Assert.That(sh.Message, Does.StartWith("Unable to acquire lock on file"),
"Expecting an error message");
}
@@ -1414,7 +1415,8 @@ public void TestMinimalLockRecovers()
log.Log(GetType(), Level.Info, "This is a message 2", null);
DestroyLogger();
- AssertFileEquals(filename, "This is a message 2" + Environment.NewLine);
+ // The retry appends to what the lock holder wrote.
+ AssertFileEquals(filename, "Test" + "This is a message 2" + Environment.NewLine);
Assert.That(sh.Message.Substring(0, 30), Is.EqualTo("Unable to acquire lock on file"),
"Expecting an error message");
}
@@ -1485,7 +1487,8 @@ public void TestInterProcessLockRecovers()
log.Log(GetType(), Level.Info, "This is a message 2", null);
DestroyLogger();
- AssertFileEquals(filename, "This is a message 2" + Environment.NewLine);
+ // The retry appends to what the lock holder wrote.
+ AssertFileEquals(filename, "Test" + "This is a message 2" + Environment.NewLine);
Assert.That(sh.Message.Substring(0, 30), Is.EqualTo("Unable to acquire lock on file"),
"Expecting an error message");
}
diff --git a/src/log4net/Appender/FileAppender.cs b/src/log4net/Appender/FileAppender.cs
index 03fbda43..1290e03d 100644
--- a/src/log4net/Appender/FileAppender.cs
+++ b/src/log4net/Appender/FileAppender.cs
@@ -469,6 +469,13 @@ public class MinimalLock : LockingModelBase
private string? _filename;
private bool _append;
private Stream? _stream;
+ private Mutex? _mutex;
+ private bool _isMutexHeld;
+
+ ///
+ /// How long to wait for the mutex before an event is dropped and reported.
+ ///
+ internal int MutexTimeoutMillis { get; set; } = 10_000;
///
/// Prepares to open the file when the first message is logged.
@@ -520,6 +527,12 @@ public override void CloseFile()
{
if (_filename is not null)
{
+ if (!TryEnterMutex())
+ {
+ CurrentAppender?.ErrorHandler.Error(
+ $"Timeout after {MutexTimeoutMillis}ms waiting for the lock on {_filename}, so the logging event was not written.");
+ return null;
+ }
try
{
_stream = CreateStream(_filename, _append, FileShare.Read);
@@ -527,6 +540,8 @@ public override void CloseFile()
}
catch (Exception e) when (!e.IsFatal())
{
+ // ReleaseLock is not called for a failed acquire.
+ ReleaseMutex();
CurrentAppender?.ErrorHandler.Error($"Unable to acquire lock on file {_filename}. {e.Message}");
}
}
@@ -550,19 +565,33 @@ public override void CloseFile()
///
public override void ReleaseLock()
{
- if (_stream is not null)
+ try
+ {
+ if (_stream is not null)
+ {
+ CloseStream(_stream);
+ }
+ }
+ finally
{
- CloseStream(_stream);
_stream = null;
+ ReleaseMutex();
}
}
///
/// Initializes all resources used by this locking model.
///
+ ///
+ /// Outside Windows a shared open lets a second writer in, so writers take turns through the mutex
+ /// uses; Windows refuses the second open already.
+ ///
public override void ActivateOptions()
{
- //NOP
+ if (_mutex is null && !SystemInfo.IsWindows && CurrentAppender?.File is string file)
+ {
+ _mutex = TryCreateMutex(MutexName(file, string.Empty));
+ }
}
///
@@ -570,7 +599,57 @@ public override void ActivateOptions()
///
public override void OnClose()
{
- //NOP
+ _mutex?.Dispose();
+ _mutex = null;
+ }
+
+ ///
+ /// Creates the named mutex, or reports once and returns where the runtime
+ /// cannot, as without a writable home directory; logging then goes on as without the mutex.
+ ///
+ internal static Mutex? TryCreateMutex(string name)
+ {
+ try
+ {
+ return new(false, name);
+ }
+ // The constructor's documented exceptions, and the one of runtimes without named mutexes.
+ catch (Exception e) when (e is IOException
+ or UnauthorizedAccessException
+ or WaitHandleCannotBeOpenedException
+ or PlatformNotSupportedException)
+ {
+ LogLog.Warn(typeof(MinimalLock),
+ $"No named mutex {name}, so other processes writing the file are not kept out. {e.Message}");
+ return null;
+ }
+ }
+
+ private bool TryEnterMutex()
+ {
+ if (_mutex is null)
+ {
+ return true;
+ }
+ try
+ {
+ _isMutexHeld = _mutex.WaitOne(MutexTimeoutMillis);
+ }
+ catch (AbandonedMutexException)
+ {
+ // The previous owner died without releasing; the wait succeeded.
+ _isMutexHeld = true;
+ }
+ return _isMutexHeld;
+ }
+
+ private void ReleaseMutex()
+ {
+ if (_isMutexHeld)
+ {
+ _isMutexHeld = false;
+ _mutex!.ReleaseMutex();
+ }
}
}
@@ -761,9 +840,7 @@ public override void ActivateOptions()
{
if (CurrentAppender.File is not null)
{
- // No ACL, Global\ prefix or user name here: without a shared ACL a global mutex
- // throws for whichever process starts second, and a user name splits one session.
- _mutex = new Mutex(false, MutexNameForPath(CurrentAppender.File, string.Empty));
+ _mutex = new Mutex(false, MutexName(CurrentAppender.File, string.Empty));
}
else
{
@@ -991,8 +1068,8 @@ public virtual string? File
///
/// There are three built in locking models, , and .
/// The first locks the file from the start of logging to the end, the
- /// second locks only for the minimal amount of time when logging each message
- /// and the last synchronizes processes using a named system-wide Mutex.
+ /// second locks only for the minimal amount of time when logging each message, outside Windows also through the named Mutex,
+ /// and the last synchronizes processes using a named Mutex, outside Windows guaranteed only for one user account on one host.
///
///
/// The default locking model is the .
@@ -1037,6 +1114,10 @@ public override void ActivateOptions()
LockingModel.CurrentAppender = this;
LockingModel.ActivateOptions();
+ if (!ImmediateFlush && LockingModel is (InterProcessLock or MinimalLock))
+ {
+ LogLog.Warn(_declaringType, "ImmediateFlush=false is ignored with InterProcessLock and MinimalLock.");
+ }
if (_fileName is not null)
{
@@ -1059,7 +1140,14 @@ public override void ActivateOptions()
///
protected override void Reset()
{
+ // A failed open leaves the stream without a writer that would close it.
+ bool hadWriter = QuietWriter is not null;
base.Reset();
+ if (!hadWriter)
+ {
+ _stream?.Dispose();
+ }
+ _stream = null;
_fileName = null;
}
@@ -1080,12 +1168,17 @@ protected override void OnClose()
/// Will be called for each logged message until the file is
/// successfully opened.
///
+ ///
+ /// Retries the last failed open, so it always appends; an appender used without
+ /// is undefined and not considered here.
+ ///
///
protected override void PrepareWriter()
{
if (_fileName is not null)
{
- SafeOpenFile(_fileName, AppendToFile);
+ // A retry never truncates, whatever the locking model.
+ SafeOpenFile(_fileName, append: true);
}
}
@@ -1113,7 +1206,7 @@ protected override void Append(LoggingEvent loggingEvent)
}
finally
{
- _stream?.ReleaseLock();
+ ReleaseLockFlushed();
}
}
}
@@ -1139,7 +1232,7 @@ protected override void Append(LoggingEvent[] loggingEvents)
}
finally
{
- _stream?.ReleaseLock();
+ ReleaseLockFlushed();
}
}
}
@@ -1154,8 +1247,11 @@ protected override void Append(LoggingEvent[] loggingEvents)
///
protected override void WriteFooter()
{
- //WriteFooter can be called even before a file is opened
- RunWithBestEffortLock(base.WriteFooter);
+ // Without a writer there is nothing to write, so no lock to wait for.
+ if (HasOpenWriter)
+ {
+ RunWithBestEffortLock(base.WriteFooter);
+ }
}
///
@@ -1168,7 +1264,7 @@ protected override void WriteFooter()
///
protected override void WriteHeader()
{
- if (_stream?.AcquireLock() ?? false)
+ if (HasOpenWriter && (_stream?.AcquireLock() ?? false))
{
try
{
@@ -1176,11 +1272,82 @@ protected override void WriteHeader()
}
finally
{
- _stream?.ReleaseLock();
+ ReleaseLockFlushed();
}
}
}
+ ///
+ /// Flushes the buffered text under the file lock; without it the locking stream refuses the write.
+ /// and flush at every release, so there is nothing to do.
+ ///
+ /// Not honoured: the wait is the locking model's.
+ /// when the file lock could not be taken or the flush failed.
+ public override bool Flush(int millisecondsTimeout)
+ {
+ if (ImmediateFlush || LockingModel is (InterProcessLock or MinimalLock))
+ {
+ return true;
+ }
+
+ // The appender lock first: the locking stream counts acquisitions, not their threads.
+ lock (LockObj)
+ {
+ if (!HasOpenWriter)
+ {
+ return true;
+ }
+ if (_stream?.AcquireLock() is not true)
+ {
+ return false;
+ }
+ try
+ {
+ return base.Flush(millisecondsTimeout);
+ }
+ finally
+ {
+ _stream.ReleaseLock();
+ }
+ }
+ }
+
+ ///
+ /// Writes the footer and closes the file within a single lock, so that no other process writes in between.
+ ///
+ protected override void WriteFooterAndCloseWriter()
+ {
+ if (HasOpenWriter)
+ {
+ RunWithBestEffortLock(base.WriteFooterAndCloseWriter);
+ }
+ else
+ {
+ // Nothing to lock for, but an overriding subclass still gets its calls.
+ base.WriteFooterAndCloseWriter();
+ }
+ }
+
+ ///
+ /// Releases the file lock. With a lock shared between processes the buffered text goes out first,
+ /// whatever says, or it would land after or over
+ /// another process's text.
+ ///
+ private void ReleaseLockFlushed()
+ {
+ try
+ {
+ if (LockingModel is (InterProcessLock or MinimalLock) && QuietWriter is { Closed: false } writer)
+ {
+ writer.Flush();
+ }
+ }
+ finally
+ {
+ _stream?.ReleaseLock();
+ }
+ }
+
///
/// Closes the underlying .
///
@@ -1192,9 +1359,17 @@ protected override void WriteHeader()
protected override void CloseWriter()
{
// An already closed writer cannot take the lock.
- RunWithBestEffortLock(base.CloseWriter);
+ if (HasOpenWriter)
+ {
+ RunWithBestEffortLock(base.CloseWriter);
+ }
}
+ ///
+ /// Whether a writer is open; after a failed open or during a roll there is none to lock for.
+ ///
+ private bool HasOpenWriter => QuietWriter is { Closed: false };
+
///
/// Closes the previously opened file.
///
@@ -1237,9 +1412,19 @@ protected virtual void SafeOpenFile(string fileName, bool append)
///
private void RunWithBestEffortLock(Action action)
{
- bool locked = _stream?.AcquireLock() ?? false;
+ // A nested call runs under the outer attempt, taken or not, instead of waiting again.
+ if (_inBestEffortLock)
+ {
+ action();
+ return;
+ }
+
+ _inBestEffortLock = true;
+ bool locked = false;
try
{
+ // Inside the try: an acquire that throws must not leave the flag set.
+ locked = _stream?.AcquireLock() ?? false;
action();
}
finally
@@ -1248,6 +1433,7 @@ private void RunWithBestEffortLock(Action action)
{
_stream?.ReleaseLock();
}
+ _inBestEffortLock = false;
}
}
@@ -1265,6 +1451,10 @@ private void RunWithBestEffortLock(Action action)
/// This method will ensure that the directory structure
/// for the specified exists.
///
+ ///
+ /// applies to this open only; keeps its
+ /// configured value.
+ ///
///
protected virtual void OpenFile(string fileName, bool append)
{
@@ -1290,9 +1480,8 @@ protected virtual void OpenFile(string fileName, bool append)
LogLog.Debug(_declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]");
- // Save these for later, allowing retries if file open fails
+ // Save it for later, allowing retries if file open fails
_fileName = fileName;
- AppendToFile = append;
LockingModel.CurrentAppender = this;
LockingModel.OpenFile(fileName, append, Encoding);
@@ -1377,8 +1566,8 @@ protected virtual void SetQWForFiles(TextWriter writer)
///
///
/// The flattened path, as earlier versions computed it. Only a name the platform rejects is
- /// hashed: Unix stops at , Windows has no limit. Unprefixed, so
- /// on Windows it coordinates one session.
+ /// hashed: Unix stops at , Windows has no limit. Unprefixed;
+ /// adds the prefix.
///
/// The suffix can collide, since it is only appended: the lock for /var/log/app_rolling and
/// the rolling lock for /var/log/app name one mutex. Two unrelated files then contend on
@@ -1389,6 +1578,13 @@ protected virtual void SetQWForFiles(TextWriter writer)
internal static string MutexNameForPath(string path, string suffix)
=> MutexNameForPath(path, suffix, SystemInfo.IsWindows ? null : MaxMutexNameBytes);
+ ///
+ /// The name of the mutex for : outside Windows with Global\, as a plain
+ /// name there is per session; on Windows without, where a global mutex needs a shared ACL.
+ ///
+ internal static string MutexName(string path, string suffix)
+ => SystemInfo.IsWindows ? MutexNameForPath(path, suffix) : @"Global\" + MutexNameForPath(path, suffix);
+
/// Takes the limit rather than deciding it, so both branches are testable anywhere.
private static string MutexNameForPath(string path, string suffix, int? maxBytes)
{
@@ -1422,6 +1618,11 @@ private static string MutexNameForPath(string path, string suffix, int? maxBytes
///
private LockingStream? _stream;
+ ///
+ /// Set while runs, always under the appender lock.
+ ///
+ private bool _inBestEffortLock;
+
///
/// The fully qualified type of the FileAppender class.
///
diff --git a/src/log4net/Appender/RollingFileAppender.cs b/src/log4net/Appender/RollingFileAppender.cs
index c6b17a31..783a6170 100644
--- a/src/log4net/Appender/RollingFileAppender.cs
+++ b/src/log4net/Appender/RollingFileAppender.cs
@@ -606,6 +606,20 @@ protected virtual void AdjustFileBeforeAppend()
}
}
+ ///
+ /// Retries a failed open with the base file name, as adds the suffix itself.
+ ///
+ protected override void PrepareWriter()
+ {
+ if (_baseFileName is null)
+ {
+ base.PrepareWriter();
+ return;
+ }
+ // A retry never truncates, as in the base class.
+ SafeOpenFile(_baseFileName, append: true);
+ }
+
///
/// Creates and opens the file for logging. If
/// is false then the fully qualified name is determined and used.
@@ -661,16 +675,7 @@ protected override void OpenFile(string fileName, bool append)
}
// Open the file (call the base class to do it)
- // base.OpenFile assigns append to AppendToFile, and can throw after doing so.
- bool configuredAppend = AppendToFile;
- try
- {
- base.OpenFile(fileName, append);
- }
- finally
- {
- AppendToFile = configuredAppend;
- }
+ base.OpenFile(fileName, append);
// Set the file size onto the counting writer. A refused lock leaves none.
(QuietWriter as CountingQuietTextWriter)?.Count = currentCount;
@@ -1156,7 +1161,7 @@ appender uses a dated file name as with StaticLogFileName false. Use a DatePatte
}
// initialize the mutex that is used to lock rolling
- _mutexForRolling = new Mutex(false, MutexNameForPath(_baseFileName, "_rolling"));
+ _mutexForRolling = new Mutex(false, MutexName(_baseFileName, "_rolling"));
if (_rollDate && File is not null && _scheduledFilename is null)
{
diff --git a/src/log4net/Appender/TextWriterAppender.cs b/src/log4net/Appender/TextWriterAppender.cs
index 44c4055b..37927329 100644
--- a/src/log4net/Appender/TextWriterAppender.cs
+++ b/src/log4net/Appender/TextWriterAppender.cs
@@ -60,12 +60,9 @@ public class TextWriterAppender : AppenderSkeleton
///
///
///
- /// Avoiding the flush operation at the end of each append results in
- /// a performance gain of 10 to 20 percent. However, there is a safety
- /// trade-off involved in skipping flushing. Indeed, when flushing is
- /// skipped, then it is likely that the last few log events will not
- /// be recorded on disk when the application exits. This is a high
- /// price to pay even for a 20% performance gain.
+ /// Skipping the flush is faster, but the last events are lost when the process ends without closing
+ /// the appender. with or
+ /// always flushes before releasing the lock.
///
public bool ImmediateFlush { get; set; } = true;
diff --git a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/fileappender.adoc b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/fileappender.adoc
index 8b76031d..e25b4104 100644
--- a/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/fileappender.adoc
+++ b/src/site/antora/modules/ROOT/pages/manual/configuration/appenders/fileappender.adoc
@@ -36,6 +36,10 @@ The file will be appended to rather than overwritten each time the logging proce
----
+If the file cannot be opened, each later event tries again.
+Such a retry never truncates, whatever the locking model, also with `appendToFile` set to `false`, so
+what another process wrote meanwhile stays.
+
This example shows how to configure the file name to write to using an environment variable TEMP.
The encoding to use to write to the file is also specified.
A character the encoding cannot represent is written as a `\uXXXX` escape, never as a best fit substitute or `?`.
@@ -70,12 +74,17 @@ This example shows how to configure the appender to use the minimal locking mode
== Waiting for the lock
`InterProcessLock` coordinates several processes writing to one file through a named mutex.
+Outside Windows `MinimalLock` takes the same mutex around each write, as a shared open does not keep a
+second writer out there; readers are not held up, and its wait is fixed at 10000 milliseconds.
+Outside Windows only the processes of one user account on one host are guaranteed to share that
+mutex, which needs a writable home directory.
The wait for it happens while the appender lock is held, so a lock nobody releases would suspend
every thread logging through the appender.
The wait is therefore bounded by `lockTimeoutMillis`, 10000 by default.
An event that cannot get the lock in time is reported through the error handler and dropped, and the
appender carries on with the next one.
+If the lock times out while the file is opened, each later event tries the open again and waits once.
Raise the value when the file is on storage where the lock is legitimately slow to obtain, such as a
network share, or set it to `-1` to wait for as long as it takes.
@@ -93,6 +102,11 @@ network share, or set it to `-1` to wait for as long as it takes.
----
+`InterProcessLock` and `MinimalLock` write out what they buffered before each release of the lock,
+so that no text lands after or over another process's; `immediateFlush` set to `false` has no effect
+with them.
+For speed put a `BufferingForwardingAppender` in front: one lock and one flush per batch.
+
`RollingFileAppender` takes a second mutex around the decision to roll and has its own
`lockTimeoutMillis` for it, with the same default.
An event that cannot get that lock is written to the current file without checking whether it should
diff --git a/src/site/antora/modules/ROOT/pages/manual/faq.adoc b/src/site/antora/modules/ROOT/pages/manual/faq.adoc
index f9333a17..04d9dca8 100644
--- a/src/site/antora/modules/ROOT/pages/manual/faq.adoc
+++ b/src/site/antora/modules/ROOT/pages/manual/faq.adoc
@@ -278,8 +278,11 @@ FileAppender offers different locking models, but they have limitations:
* **Default** - Holds an exclusive write lock, preventing other processes from writing.
* **MinimalLock** - Acquires the write lock only while logging, allowing interleaved writes but with significant performance loss.
-* **InterProcessLock** - Uses a system-wide Mutex to synchronize, but requires all processes to cooperate.
+Outside Windows it also takes the named Mutex of InterProcessLock.
+* **InterProcessLock** - Uses a named Mutex to synchronize, but requires all processes to cooperate.
While better than MinimalLock, it still causes performance issues due to frequent Mutex acquisition.
+Outside Windows only processes of one user account on one host are guaranteed to share it.
+MinimalLock and InterProcessLock flush before each release of the lock, whatever `immediateFlush` says.
* **NoLock** - Does not use any lock, allowing all processes to write simultaneously.
However, this can lead to log data corruption if multiple processes write to the file at the same time.