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 index a91254a6..706476a9 100644 --- a/src/changelog/3.6.1/368-retried-open-suffix-once.xml +++ b/src/changelog/3.6.1/368-retried-open-suffix-once.xml @@ -7,5 +7,5 @@ `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) + file behind (ANT-2026-VPDB2R3O, fixed by @FreeAndNil) diff --git a/src/changelog/3.6.1/377-remote-syslog-undefined-newline-escapes.xml b/src/changelog/3.6.1/377-remote-syslog-undefined-newline-escapes.xml new file mode 100644 index 00000000..9a4b42aa --- /dev/null +++ b/src/changelog/3.6.1/377-remote-syslog-undefined-newline-escapes.xml @@ -0,0 +1,11 @@ + + + + + `RemoteSyslogAppender` escapes CR and LF for a `NewLineHandling` other + than `Keep` and `Split`, also for an undefined value set after activation, which dropped them + (fixed by @FreeAndNil) + diff --git a/src/changelog/3.6.1/378-write-without-named-mutex.xml b/src/changelog/3.6.1/378-write-without-named-mutex.xml new file mode 100644 index 00000000..c17b87d9 --- /dev/null +++ b/src/changelog/3.6.1/378-write-without-named-mutex.xml @@ -0,0 +1,12 @@ + + + + + `RollingFileAppender` and `InterProcessLock` no longer fail activation when + their named mutex cannot be created, as outside Windows without a writable home directory. They write + without it and warn once, as `MinimalLock` does; other processes may then write the same file at + the same time (fixed by @FreeAndNil) + diff --git a/src/changelog/3.6.1/379-file-name-variable-expanded-once.xml b/src/changelog/3.6.1/379-file-name-variable-expanded-once.xml new file mode 100644 index 00000000..63412f83 --- /dev/null +++ b/src/changelog/3.6.1/379-file-name-variable-expanded-once.xml @@ -0,0 +1,13 @@ + + + + + Expand environment variables such as `%COMPUTERNAME%` in the file name of + `FileAppender` and `RollingFileAppender` before the path is made absolute. + `RollingFileAppender` rolled under the unexpanded name, found nothing to rename and reopened the + live file truncated, so every roll lost the log (ANT-2026-O4KAKTUN). A variable that holds a + rooted path, such as `%TEMP%/app.log`, is no longer placed under the application base directory (fixed by @FreeAndNil) + diff --git a/src/changelog/3.6.1/379-second-activation-follows-the-file.xml b/src/changelog/3.6.1/379-second-activation-follows-the-file.xml new file mode 100644 index 00000000..a681ad0f --- /dev/null +++ b/src/changelog/3.6.1/379-second-activation-follows-the-file.xml @@ -0,0 +1,13 @@ + + + + + A second `ActivateOptions` of `FileAppender` and `RollingFileAppender` closes the old + file first. `MinimalLock`, `InterProcessLock` and the rolling mutex follow a changed `File`, the + same file keeps its mutex, and `InterProcessLock` no longer reports a programming error. + `RollingFileAppender` keeps the configured file name as its base, so the roll suffix is no longer + added again, and date rolls rename the new file (fixed by @FreeAndNil) + diff --git a/src/log4net.Tests/Appender/FileReactivationTest.cs b/src/log4net.Tests/Appender/FileReactivationTest.cs new file mode 100644 index 00000000..e178c168 --- /dev/null +++ b/src/log4net.Tests/Appender/FileReactivationTest.cs @@ -0,0 +1,318 @@ +#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.Linq; +using System.Runtime.InteropServices; +using System.Threading; + +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 file name with an environment variable, and a second ActivateOptions (#379). +/// +[TestFixture] +[NonParallelizable] +public sealed class FileReactivationTest +{ + private const string Variable = "LOG4NET_TEST_379"; + + /// Clears the variable the tests set. + [TearDown] + public void ClearVariable() => Environment.SetEnvironmentVariable(Variable, null); + + /// + /// The roll used to look for the unexpanded name, found nothing and reopened the live file + /// truncated, so every roll lost the log. + /// + [Test] + public void RollingKeepsEveryEventWithAVariableInTheFileName() + { + using AutoTempFolder folder = new(); + Environment.SetEnvironmentVariable(Variable, "web01"); + RecordingErrorHandler errors = new(); + RollingFileAppender appender = new() + { + File = Path.Combine(folder.Path, $"audit-%{Variable}%.log"), + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Size, + MaxFileSize = 100, + MaxSizeRollBackups = 10, + ErrorHandler = errors + }; + appender.ActivateOptions(); + for (int i = 0; i < 10; i++) + { + appender.DoAppend(CreateEvent($"event {i} of the audit log")); + } + appender.Close(); + + string[] names = [.. Directory.GetFiles(folder.Path).Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal)!]; + string all = string.Concat(Directory.GetFiles(folder.Path).Select(File.ReadAllText)); + Assert.That(names, Does.Contain("audit-web01.log").And.Contain("audit-web01.log.1")); + Assert.That(names, Has.None.Contains("%")); + for (int i = 0; i < 10; i++) + { + Assert.That(all, Does.Contain($"event {i} of the audit log")); + } + Assert.That(errors.Messages, Is.Empty); + } + + /// A variable whose value holds another one names the same file for rolling and writing. + [Test] + public void RollingKeepsEveryEventWithANestedVariable() + { + using AutoTempFolder folder = new(); + Environment.SetEnvironmentVariable(Variable, $"%{Variable}_INNER%"); + Environment.SetEnvironmentVariable(Variable + "_INNER", "inner"); + try + { + RollingFileAppender appender = new() + { + File = Path.Combine(folder.Path, $"app-%{Variable}%.log"), + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Size, + MaxFileSize = 60, + MaxSizeRollBackups = 10 + }; + appender.ActivateOptions(); + for (int i = 0; i < 8; i++) + { + appender.DoAppend(CreateEvent($"nested event {i}")); + } + appender.Close(); + } + finally + { + Environment.SetEnvironmentVariable(Variable + "_INNER", null); + } + + string all = string.Concat(Directory.GetFiles(folder.Path).Select(File.ReadAllText)); + for (int i = 0; i < 8; i++) + { + Assert.That(all, Does.Contain($"nested event {i}")); + } + } + + /// A variable that expands to a rooted path stays rooted. + [Test] + public void VariableExpandingToARootedPathIsNotPutUnderTheBaseDirectory() + { + using AutoTempFolder folder = new(); + Environment.SetEnvironmentVariable(Variable, folder.Path); + FileAppender appender = CreateAppender($"%{Variable}%/app.log", new FileAppender.ExclusiveLock()); + + appender.ActivateOptions(); + string? file = appender.File; + appender.DoAppend(CreateEvent("rooted")); + appender.Close(); + + Assert.That(file, Is.EqualTo(Path.Combine(folder.Path, "app.log"))); + Assert.That(File.ReadAllText(Path.Combine(folder.Path, "app.log")), Does.Contain("rooted")); + } + + /// Each activation used to take the opened name as the base and add the suffix again. + [Test] + public void SecondActivationKeepsTheRollingFileName() + { + using AutoTempFolder folder = new(); + RollingFileAppender appender = new() + { + File = Path.Combine(folder.Path, "r.log"), + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Size, + StaticLogFileName = false, + CountDirection = 1 + }; + for (int i = 0; i < 3; i++) + { + appender.ActivateOptions(); + appender.DoAppend(CreateEvent($"activation {i}")); + } + appender.Close(); + + string[] names = [.. Directory.GetFiles(folder.Path).Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal)!]; + Assert.That(names, Is.EqualTo(new[] { "r.log.0" })); + Assert.That(File.ReadAllText(Path.Combine(folder.Path, "r.log.0")), + Does.Contain("activation 0").And.Contain("activation 2")); + } + + /// + /// The locking models kept the mutex named after the old file, so a second process writing the + /// new file was not kept out; InterProcessLock also reported a programming error. + /// + /// The locking model, by name. + [TestCase("MinimalLock")] + [TestCase("InterProcessLock")] + public void SecondActivationMovesTheLockMutexToTheNewFile(string lockingModel) + { + if (lockingModel == "MinimalLock" && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + Assert.Ignore("MinimalLock takes no mutex on Windows"); + } + using AutoTempFolder folder = new(); + string first = Path.Combine(folder.Path, "a.log"); + string second = Path.Combine(folder.Path, "b.log"); + FileAppender appender = CreateAppender(first, lockingModel == "MinimalLock" + ? new FileAppender.MinimalLock() + : new FileAppender.InterProcessLock()); + + List<(string Name, Mutex Mutex)> created = RecordMutexes(() => + { + appender.ActivateOptions(); + appender.ActivateOptions(); + appender.File = second; + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("second file")); + appender.Close(); + }); + + Assert.That(created.Select(m => m.Name).ToArray(), Is.EqualTo(new[] + { + MutexName(first, string.Empty), + MutexName(second, string.Empty) + })); + Assert.That(created[0].Mutex.SafeWaitHandle.IsClosed, Is.True, "the old file's mutex is released"); + Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty); + Assert.That(File.ReadAllText(second), Does.Contain("second file")); + } + + /// Each activation created a new rolling mutex and left the old one open. + [Test] + public void SecondActivationReusesOrReplacesTheRollingMutex() + { + using AutoTempFolder folder = new(); + string first = Path.Combine(folder.Path, "r.log"); + string second = Path.Combine(folder.Path, "s.log"); + RollingFileAppender appender = new() + { + File = first, + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Size + }; + + List<(string Name, Mutex Mutex)> created = RecordMutexes(() => + { + appender.ActivateOptions(); + appender.ActivateOptions(); + appender.File = second; + appender.ActivateOptions(); + appender.Close(); + }); + + string[] rolling = [.. created.Select(m => m.Name).Where(n => n.EndsWith("_rolling", StringComparison.Ordinal))]; + Assert.That(rolling, Is.EqualTo(new[] + { + MutexName(first, "_rolling"), + MutexName(second, "_rolling") + })); + Assert.That(created.First(m => m.Name == rolling[0]).Mutex.SafeWaitHandle.IsClosed, Is.True); + } + + /// A date roll after an activation with another file renames that file, not the old one. + [Test] + public void DateRollAfterSecondActivationNamesTheNewFile() + { + using AutoTempFolder folder = new(); + Integration.MockDateTime clock = new(new(2026, 10, 4, 9, 0, 0)); + RollingFileAppender appender = new() + { + File = Path.Combine(folder.Path, "r.log"), + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Date, + DatePattern = ".yyyy-MM-dd", + DateTimeStrategy = clock + }; + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("r first day")); + appender.File = Path.Combine(folder.Path, "s.log"); + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("s first day")); + clock.Now = new(2026, 10, 5, 9, 0, 0); + appender.DoAppend(CreateEvent("s second day")); + appender.Close(); + + string[] names = [.. Directory.GetFiles(folder.Path).Select(Path.GetFileName).OrderBy(n => n, StringComparer.Ordinal)!]; + Assert.That(names, Is.EqualTo(new[] { "r.log", "s.log", "s.log.2026-10-04" })); + Assert.That(File.ReadAllText(Path.Combine(folder.Path, "s.log.2026-10-04")), Does.Contain("s first day")); + } + + /// + /// The roll of a second activation used to meet the file of the first still open, which Windows + /// refuses to rename. + /// + [Test] + [Platform("Win")] + public void SecondActivationRollsTheFileOfTheFirst() + { + using AutoTempFolder folder = new(); + string file = Path.Combine(folder.Path, "r.log"); + RollingFileAppender appender = new() + { + File = file, + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Once, + MaxSizeRollBackups = 1 + }; + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("first activation")); + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("second activation")); + appender.Close(); + + Assert.That(File.ReadAllText(file + ".1"), Does.Contain("first activation")); + Assert.That(File.ReadAllText(file), Does.Contain("second activation").And.Not.Contain("first activation")); + } + + private static string MutexName(string path, string suffix) + => typeof(FileAppender).Invoke(nameof(MutexName), [path, suffix]); + + private static List<(string Name, Mutex Mutex)> RecordMutexes(Action action) + { + List<(string Name, Mutex Mutex)> created = []; + Func original = typeof(FileAppender).GetFieldValue>("_mutexFactory"); + typeof(FileAppender).SetFieldValue("_mutexFactory", new Func(name => + { + Mutex mutex = original(name); + created.Add((name, mutex)); + return mutex; + })); + try + { + action(); + } + finally + { + typeof(FileAppender).SetFieldValue("_mutexFactory", original); + } + return created; + } +} diff --git a/src/log4net.Tests/Appender/MinimalLockMutexTest.cs b/src/log4net.Tests/Appender/MinimalLockMutexTest.cs index 63928244..10b72a42 100644 --- a/src/log4net.Tests/Appender/MinimalLockMutexTest.cs +++ b/src/log4net.Tests/Appender/MinimalLockMutexTest.cs @@ -128,7 +128,7 @@ public void AMutexThatCannotBeCreatedIsReportedOnce() { using LogLog.LogReceivedAdapter _ = new(messages); // A name the runtime refuses with the same IOException. - mutex = typeof(FileAppender.MinimalLock).Invoke("TryCreateMutex", ["Global\\no/such"]); + mutex = typeof(FileAppender).Invoke("TryCreateMutex", ["Global\\no/such", "nothing"]); }); Assert.That(mutex, Is.Null); diff --git a/src/log4net.Tests/Appender/MutexFallbackTest.cs b/src/log4net.Tests/Appender/MutexFallbackTest.cs new file mode 100644 index 00000000..eaa06116 --- /dev/null +++ b/src/log4net.Tests/Appender/MutexFallbackTest.cs @@ -0,0 +1,127 @@ +#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; + +/// +/// Appenders whose named mutex cannot be created, as without a writable home directory, log without it. +/// +[TestFixture] +[NonParallelizable] +public sealed class MutexFallbackTest +{ + /// + /// A activates, logs and rolls, with one warning naming the roll. + /// + [Test] + public void RollingWithoutANamedMutexLogsAndRolls() + { + using AutoTempFolder folder = new(); + string file = Path.Combine(folder.Path, "r.log"); + RecordingErrorHandler errors = new(); + RollingFileAppender appender = new() + { + File = file, + Layout = new PatternLayout("%message%newline"), + RollingStyle = RollingFileAppender.RollingMode.Size, + MaxFileSize = 10, + MaxSizeRollBackups = 2, + ErrorHandler = errors + }; + + List messages = WithFailingMutexes(() => + { + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("first event")); + appender.DoAppend(CreateEvent("second event")); + appender.Close(); + }); + + Assert.That(File.ReadAllText(file + ".1"), Does.Contain("first event")); + Assert.That(File.ReadAllText(file), Does.Contain("second event")); + Assert.That(messages, Has.Count.EqualTo(1)); + Assert.That(messages[0].Message, Does.Contain("other processes may roll the same files at the same time")); + Assert.That(errors.Messages, Is.Empty); + } + + /// + /// activates and logs, with one warning and no error report. + /// + [Test] + public void InterProcessLockWithoutANamedMutexLogs() + { + using AutoTempFolder folder = new(); + string file = Path.Combine(folder.Path, "ipl.log"); + FileAppender appender = CreateAppender(file, new FileAppender.InterProcessLock()); + + List messages = WithFailingMutexes(() => + { + appender.ActivateOptions(); + appender.DoAppend(CreateEvent("written")); + appender.Close(); + }); + + Assert.That(File.ReadAllText(file), Does.Contain("written")); + Assert.That(messages, Has.Count.EqualTo(1)); + Assert.That(messages[0].Message, Does.Contain("other processes may write the file at the same time")); + Assert.That(((RecordingErrorHandler)appender.ErrorHandler).Messages, Is.Empty); + } + + /// + /// Runs with a mutex factory that fails as the runtime does without a + /// writable home, and returns the internal messages. + /// + private static List WithFailingMutexes(Action action) + { + List messages = []; + Func original = typeof(FileAppender).GetFieldValue>("_mutexFactory"); + typeof(FileAppender).SetFieldValue("_mutexFactory", + new Func(_ => throw new IOException("simulated: no writable home"))); + try + { + LogLog.ExecuteWithoutEmittingInternalMessages(() => + { + using LogLog.LogReceivedAdapter _ = new(messages); + action(); + }); + } + finally + { + typeof(FileAppender).SetFieldValue("_mutexFactory", original); + } + return messages; + } +} diff --git a/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs b/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs index 44ae0edd..566fa7ae 100644 --- a/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs +++ b/src/log4net.Tests/Appender/RemoteSyslogAppenderTest.cs @@ -241,6 +241,26 @@ public void RemoteSyslogNewLineHandlingSplitTest() Assert.That(Encoding.ASCII.GetString(sentBytes[1]), Is.EqualTo(expectedData1)); } + /// + /// takes an LF CR pair as one break, and a trailing break + /// sends no empty record. + /// + [TestCase("Test\r", 1, TestName = "TrailingCr")] + [TestCase("Test\n\rmessage", 2, TestName = "LfCrPair")] + public void SplitTakesAPairAsOneBreak(string message, int records) + => Assert.That(ExecuteAppend(message, SyslogNewLineHandling.Split), Has.Count.EqualTo(records)); + + /// + /// An undefined value set after activation escapes CR and LF instead of dropping them. + /// + [Test] + public void AnUndefinedNewLineHandlingSetLaterEscapes() + { + List sentBytes = ExecuteAppend("Test\r\nmessage", laterNewLineHandling: (SyslogNewLineHandling)5); + Assert.That(sentBytes, Has.Count.EqualTo(1)); + Assert.That(Encoding.ASCII.GetString(sentBytes[0]), Is.EqualTo(@"<14>TestDomain: INFO - Test\r\nmessage")); + } + /// /// The Identity becomes the TAG of the record. A control character in it would end the record, /// so that the rest is read as a second record with its own facility and severity. @@ -481,7 +501,8 @@ private static List ExecuteAppend(string message, SyslogNewLineHandling newLineHandling = default, string? identity = null, int? maxDatagramSize = null, - Encoding? encoding = null) + Encoding? encoding = null, + SyslogNewLineHandling? laterNewLineHandling = null) { System.Net.IPAddress ipAddress = new([127, 0, 0, 1]); RemoteAppender appender = new() @@ -500,6 +521,10 @@ private static List ExecuteAppend(string message, appender.Encoding = encoding; } appender.ActivateOptions(); + if (laterNewLineHandling is SyslogNewLineHandling later) + { + appender.NewLineHandling = later; + } LoggingEvent loggingEvent = new(new() { Level = Level.Info, diff --git a/src/log4net/Appender/FileAppender.cs b/src/log4net/Appender/FileAppender.cs index 71c7783a..1fe16c41 100644 --- a/src/log4net/Appender/FileAppender.cs +++ b/src/log4net/Appender/FileAppender.cs @@ -322,7 +322,7 @@ public abstract class LockingModelBase /// protected Stream CreateStream(string filename, bool append, FileShare fileShare) { - filename = Environment.ExpandEnvironmentVariables(filename); + filename = ExpandVariables(filename); using (CurrentAppender?.SecurityContext?.Impersonate(this)) { // Ensure that the directory structure exists @@ -470,6 +470,7 @@ public class MinimalLock : LockingModelBase private bool _append; private Stream? _stream; private Mutex? _mutex; + private string? _mutexName; private bool _isMutexHeld; /// @@ -588,9 +589,19 @@ public override void ReleaseLock() /// public override void ActivateOptions() { - if (_mutex is null && !SystemInfo.IsWindows && CurrentAppender?.File is string file) + // Windows refuses a second open already, so the mutex is needed only elsewhere. + string? name = null; + if (!SystemInfo.IsWindows && CurrentAppender?.File is string file) { - _mutex = TryCreateMutex(MutexName(file, string.Empty)); + name = MutexName(file, string.Empty); + } + + // A later activation with another file takes that file's mutex; the same file keeps its own. + if (name != _mutexName) + { + _mutex?.Dispose(); + _mutex = name is null ? null : TryCreateMutex(name, ConcurrentWrites); + _mutexName = name; } } @@ -601,28 +612,7 @@ public override void OnClose() { _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; - } + _mutexName = null; } private bool TryEnterMutex() @@ -661,6 +651,7 @@ private void ReleaseMutex() public class InterProcessLock : LockingModelBase { private Mutex? _mutex; + private string? _mutexName; private Stream? _stream; private int _recursiveWatch; private int _lockTimeoutMillis = 10_000; @@ -834,23 +825,25 @@ public override void ReleaseLock() /// public override void ActivateOptions() { - if (_mutex is null) + if (CurrentAppender is null) { - if (CurrentAppender is not null) - { - if (CurrentAppender.File is not null) - { - _mutex = new Mutex(false, MutexName(CurrentAppender.File, string.Empty)); - } - else - { - CurrentAppender.ErrorHandler.Error($"Current appender has no file name, {nameof(OpenFile)} not called or it encountered an error"); - } - } + return; } - else + if (CurrentAppender.File is null) { - CurrentAppender?.ErrorHandler.Error("Programming error, mutex already initialized!"); + CurrentAppender.ErrorHandler.Error($"Current appender has no file name, {nameof(OpenFile)} not called or it encountered an error"); + return; + } + + // A later activation with another file takes that file's mutex; the same file keeps its own. + string name = MutexName(CurrentAppender.File, string.Empty); + if (_mutex is null || name != _mutexName) + { + _mutex?.Dispose(); + _mutex = TryCreateMutex(name, ConcurrentWrites); + // Unnamed if the named one fails: this process still serializes, the warning says the rest. + _mutex ??= new(false); + _mutexName = name; } } @@ -863,6 +856,7 @@ public override void OnClose() { _mutex.Dispose(); _mutex = null; + _mutexName = null; } else { @@ -1103,30 +1097,47 @@ public override void ActivateOptions() SecurityContext ??= SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); - if (_fileName is not null) + lock (LockObj) { - using (SecurityContext.Impersonate(this)) + CloseEarlierFile(); + if (_fileName is not null) { - // Before the locking model activates, which names its mutex after this path. - _fileName = ConvertToFullPath(_fileName.Trim()); + using (SecurityContext.Impersonate(this)) + { + // Before the locking model activates, which names its mutex after this path. + _fileName = ConvertToFullPath(_fileName.Trim()); + } } - } - LockingModel.CurrentAppender = this; - LockingModel.ActivateOptions(); - if (!ImmediateFlush && LockingModel is (InterProcessLock or MinimalLock)) - { - LogLog.Warn(_declaringType, "ImmediateFlush=false is ignored with InterProcessLock and MinimalLock."); - } + 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) - { - SafeOpenFile(_fileName, AppendToFile); + if (_fileName is not null) + { + SafeOpenFile(_fileName, AppendToFile); + } + else + { + LogLog.Warn(_declaringType, "FileAppender: File option not set for appender [" + Name + "]."); + LogLog.Warn(_declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); + } } - else + } + + /// + /// Closes the file of an earlier activation, so the locking model and a roll never meet it open. + /// + private protected void CloseEarlierFile() + { + if (QuietWriter is not null || _stream is not null) { - LogLog.Warn(_declaringType, "FileAppender: File option not set for appender [" + Name + "]."); - LogLog.Warn(_declaringType, "FileAppender: Are you using FileAppender instead of ConsoleAppender?"); + string? fileName = _fileName; + Reset(); + _fileName = fileName; } } @@ -1557,8 +1568,33 @@ protected virtual void SetQWForFiles(TextWriter writer) /// taken as relative from the application base /// directory. /// + /// + /// Environment variables such as %COMPUTERNAME% are expanded first, so a variable that + /// holds a rooted path stays rooted. + /// /// - protected static string ConvertToFullPath(string path) => SystemInfo.ConvertToFullPath(path); + protected static string ConvertToFullPath(string path) + => SystemInfo.ConvertToFullPath(ExpandVariables(path)); + + /// + /// Expands environment variables until nothing changes, so every later expansion of the result is a no-op. + /// + /// The path to expand. + /// The expanded path. + private static string ExpandVariables(string path) + { + // A variable whose value names itself would loop forever; ten rounds end it. + for (int i = 0; i < 10; i++) + { + string expanded = Environment.ExpandEnvironmentVariables(path); + if (expanded == path) + { + break; + } + path = expanded; + } + return path; + } /// /// Names the mutex that serialises between processes, with @@ -1608,6 +1644,35 @@ private static string MutexNameForPath(string path, string suffix, int? maxBytes /// The longest mutex name Unix accepts, in UTF-8 bytes. Windows has no limit. Measured. private const int MaxMutexNameBytes = 255; + /// What the lock models risk without their named mutex, for the warning. + internal const string ConcurrentWrites = "other processes may write the file at the same time"; + + /// Creates a named mutex; a test replaces it with one that fails. + private static Func _mutexFactory = name => new(false, name); + + /// + /// Creates the named mutex, or reports once and returns where the runtime + /// cannot, as without a writable home directory. + /// + /// The name of the mutex. + /// What is lost without it, for the warning. + internal static Mutex? TryCreateMutex(string name, string consequence) + { + try + { + return _mutexFactory(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(_declaringType, $"No named mutex {name}, so {consequence}. {e.Message}"); + return null; + } + } + /// /// The name of the log file. /// diff --git a/src/log4net/Appender/RemoteSyslogAppender.cs b/src/log4net/Appender/RemoteSyslogAppender.cs index 5e8848aa..0ac13501 100644 --- a/src/log4net/Appender/RemoteSyslogAppender.cs +++ b/src/log4net/Appender/RemoteSyslogAppender.cs @@ -462,30 +462,22 @@ protected virtual void AppendMessage(string message, ref int characterIndex, Str { builder.Append(c); } - // If character is newline - else if (c is '\r' or '\n') + else if (HasBreakAt(characterIndex)) { - if (NewLineHandling == SyslogNewLineHandling.Escape) + if (NewLineHandling == SyslogNewLineHandling.Split) { - // escape - builder.Append(c == '\r' ? "\\r" : "\\n"); + // A break and the one right after it count as one; the next record starts after them. + characterIndex += HasBreakAt(characterIndex + 1) ? 2 : 1; + return; } - else if (NewLineHandling == SyslogNewLineHandling.Keep) + if (NewLineHandling == SyslogNewLineHandling.Keep) { - // keep builder.Append(c); } - else if (NewLineHandling == SyslogNewLineHandling.Split) + else { - // break and send the current line - // Check the next character to handle \r\n or \n\r - if ((message.Length > characterIndex + 1) - && ((message[characterIndex + 1] == '\r') || (message[characterIndex + 1] == '\n'))) - { - characterIndex++; - } - characterIndex++; - break; + // Escape, also for undefined values. + builder.Append(c == '\r' ? "\\r" : "\\n"); } } else @@ -495,6 +487,8 @@ protected virtual void AppendMessage(string message, ref int characterIndex, Str builder.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); } } + + bool HasBreakAt(int index) => index < message.Length && message[index] is '\r' or '\n'; } /// diff --git a/src/log4net/Appender/RollingFileAppender.cs b/src/log4net/Appender/RollingFileAppender.cs index 178a9c4e..934d6f4a 100644 --- a/src/log4net/Appender/RollingFileAppender.cs +++ b/src/log4net/Appender/RollingFileAppender.cs @@ -1112,8 +1112,28 @@ public static RollPoint ComputeCheckPeriod(string datePattern) /// /// public override void ActivateOptions() + { + lock (LockObj) + { + ActivateOptionsLocked(); + } + } + + /// + public override string? File + { + get => base.File; + set + { + base.File = value; + _configuredFile = value; + } + } + + private void ActivateOptionsLocked() { _pendingRename = null; + CloseEarlierFile(); if (_rollDate && DatePattern is not null) { @@ -1154,14 +1174,25 @@ appender uses a dated file name as with StaticLogFileName false. Use a DatePatte // Must convert the FileAppender's filePath to an absolute path before we // call ExistingInit(). This will be done by the base.ActivateOptions() but // we need to duplicate that functionality here first. - base.File = ConvertToFullPath(base.File!.Trim()); + string baseFileName = ConvertToFullPath((_configuredFile ?? base.File)!.Trim()); + if (baseFileName != _baseFileName) + { + _scheduledFilename = null; + } + base.File = baseFileName; // Store fully qualified base file name - _baseFileName = base.File; + _baseFileName = baseFileName; } - // initialize the mutex that is used to lock rolling - _mutexForRolling = new Mutex(false, MutexName(_baseFileName, "_rolling")); + // The mutex that locks rolling follows the base file name; the old one is released. + string rollingMutexName = MutexName(_baseFileName, "_rolling"); + if (rollingMutexName != _rollingMutexName) + { + Interlocked.Exchange(ref _mutexForRolling, null)?.Dispose(); + _mutexForRolling = TryCreateMutex(rollingMutexName, ConcurrentRolls); + _rollingMutexName = rollingMutexName; + } if (_rollDate && File is not null && _scheduledFilename is null) { @@ -1775,6 +1806,15 @@ protected static DateTime NextCheckDate(DateTime currentDateTime, RollPoint roll /// private Mutex? _mutexForRolling; + /// The name was created with. + private string? _rollingMutexName; + + /// The file name as configured, before activation turns it into the opened name. + private string? _configuredFile; + + /// What rolling risks without its named mutex, for the warning. + private const string ConcurrentRolls = "other processes may roll the same files at the same time"; + private int _lockTimeoutMillis = 10_000; /// 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 e25b4104..42f90480 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 @@ -56,6 +56,10 @@ A character the encoding cannot represent is written as a `\uXXXX` escape, never ---- +The appender also expands `%TEMP%`-style variables in the file name, before it makes the path absolute. +A variable that holds a rooted path stays rooted. +`RollingFileAppender` rolls under the expanded name. + This example shows how to configure the appender to use the minimal locking model that allows multiple processes to write to the same file. [source,xml] @@ -78,6 +82,7 @@ Outside Windows `MinimalLock` takes the same mutex around each write, as a share 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. +If the home directory is missing or read-only, the appender writes without the mutex and warns once. The wait for it happens while the appender lock is held, so a lock nobody releases would suspend every thread logging through the appender. 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 92dd1159..9de627cf 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 @@ -106,7 +106,7 @@ logger.Error("A\nB\r\nC"); Output (one syslog entry): [source,log] -... ERROR ... - A\nB\rC +... ERROR ... - A\nB\r\nC === Example: Split