Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/changelog/3.6.1/368-retried-open-suffix-once.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
<issue id="369" link="https://github.com/apache/logging-log4net/pull/369"/>
<description format="asciidoc">`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)</description>
file behind (ANT-2026-VPDB2R3O, fixed by @FreeAndNil)</description>
</entry>
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="377" link="https://github.com/apache/logging-log4net/issues/377"/>
<issue id="380" link="https://github.com/apache/logging-log4net/pull/380"/>
<description format="asciidoc">`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)</description>
</entry>
12 changes: 12 additions & 0 deletions src/changelog/3.6.1/378-write-without-named-mutex.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="378" link="https://github.com/apache/logging-log4net/issues/378"/>
<issue id="380" link="https://github.com/apache/logging-log4net/pull/380"/>
<description format="asciidoc">`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)</description>
</entry>
13 changes: 13 additions & 0 deletions src/changelog/3.6.1/379-file-name-variable-expanded-once.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="379" link="https://github.com/apache/logging-log4net/issues/379"/>
<issue id="380" link="https://github.com/apache/logging-log4net/pull/380"/>
<description format="asciidoc">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)</description>
</entry>
13 changes: 13 additions & 0 deletions src/changelog/3.6.1/379-second-activation-follows-the-file.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://logging.apache.org/xml/ns"
xsi:schemaLocation="https://logging.apache.org/xml/ns https://logging.apache.org/xml/ns/log4j-changelog-0.xsd"
type="fixed">
<issue id="379" link="https://github.com/apache/logging-log4net/issues/379"/>
<issue id="380" link="https://github.com/apache/logging-log4net/pull/380"/>
<description format="asciidoc">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)</description>
</entry>
318 changes: 318 additions & 0 deletions src/log4net.Tests/Appender/FileReactivationTest.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// A file name with an environment variable, and a second <c>ActivateOptions</c> (#379).
/// </summary>
[TestFixture]
[NonParallelizable]
public sealed class FileReactivationTest
{
private const string Variable = "LOG4NET_TEST_379";

/// <summary>Clears the variable the tests set.</summary>
[TearDown]
public void ClearVariable() => Environment.SetEnvironmentVariable(Variable, null);

/// <summary>
/// The roll used to look for the unexpanded name, found nothing and reopened the live file
/// truncated, so every roll lost the log.
/// </summary>
[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);
}

/// <summary>A variable whose value holds another one names the same file for rolling and writing.</summary>
[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}"));
}
}

/// <summary>A variable that expands to a rooted path stays rooted.</summary>
[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"));
}

/// <summary>Each activation used to take the opened name as the base and add the suffix again.</summary>
[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"));
}

/// <summary>
/// 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.
/// </summary>
/// <param name="lockingModel">The locking model, by name.</param>
[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"));
}

/// <summary>Each activation created a new rolling mutex and left the old one open.</summary>
[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);
}

/// <summary>A date roll after an activation with another file renames that file, not the old one.</summary>
[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"));
}

/// <summary>
/// The roll of a second activation used to meet the file of the first still open, which Windows
/// refuses to rename.
/// </summary>
[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<string>(nameof(MutexName), [path, suffix]);

private static List<(string Name, Mutex Mutex)> RecordMutexes(Action action)
{
List<(string Name, Mutex Mutex)> created = [];
Func<string, Mutex> original = typeof(FileAppender).GetFieldValue<Func<string, Mutex>>("_mutexFactory");
typeof(FileAppender).SetFieldValue("_mutexFactory", new Func<string, Mutex>(name =>
{
Mutex mutex = original(name);
created.Add((name, mutex));
return mutex;
}));
try
{
action();
}
finally
{
typeof(FileAppender).SetFieldValue("_mutexFactory", original);
}
return created;
}
}
2 changes: 1 addition & 1 deletion src/log4net.Tests/Appender/MinimalLockMutexTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Mutex?>("TryCreateMutex", ["Global\\no/such"]);
mutex = typeof(FileAppender).Invoke<Mutex?>("TryCreateMutex", ["Global\\no/such", "nothing"]);
});

Assert.That(mutex, Is.Null);
Expand Down
Loading
Loading