diff --git a/src/log4net.Tests/Appender/AdoNetAppenderTest.cs b/src/log4net.Tests/Appender/AdoNetAppenderTest.cs
index 95106ecf..17b4119e 100644
--- a/src/log4net.Tests/Appender/AdoNetAppenderTest.cs
+++ b/src/log4net.Tests/Appender/AdoNetAppenderTest.cs
@@ -53,7 +53,7 @@ public void NoBufferingTest()
ILog log = LogManager.GetLogger(rep.Name, "NoBufferingTest");
log.Debug("Message");
Assert.That(Log4NetCommand.MostRecentInstance, Is.Not.Null);
- Assert.That(Log4NetCommand.MostRecentInstance!.ExecuteNonQueryCount, Is.EqualTo(1));
+ Assert.That(Log4NetCommand.MostRecentInstance.ExecuteNonQueryCount, Is.EqualTo(1));
}
[Test]
@@ -61,7 +61,7 @@ public void BufferingTest()
{
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
- int bufferSize = 5;
+ const int bufferSize = 5;
AdoNetAppender adoNetAppender = new()
{
@@ -80,69 +80,71 @@ public void BufferingTest()
}
log.Debug("Message");
Assert.That(Log4NetCommand.MostRecentInstance, Is.Not.Null);
- Assert.That(Log4NetCommand.MostRecentInstance!.ExecuteNonQueryCount, Is.EqualTo(bufferSize + 1));
+ Assert.That(Log4NetCommand.MostRecentInstance.ExecuteNonQueryCount, Is.EqualTo(bufferSize + 1));
}
[Test]
public void WebsiteExample()
{
XmlDocument log4NetConfig = new();
- log4NetConfig.LoadXml(@"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ");
+ log4NetConfig.LoadXml(
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
XmlConfigurator.Configure(rep, log4NetConfig["log4net"]!);
@@ -173,62 +175,64 @@ public void WebsiteExample()
public void BufferingWebsiteExample()
{
XmlDocument log4NetConfig = new();
- log4NetConfig.LoadXml(@"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ");
+ log4NetConfig.LoadXml(
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
XmlConfigurator.Configure(rep, log4NetConfig["log4net"]!);
@@ -242,7 +246,7 @@ public void BufferingWebsiteExample()
IDbCommand? command = Log4NetCommand.MostRecentInstance;
Assert.That(command, Is.Not.Null);
- Assert.That(command!.CommandText,
+ Assert.That(command.CommandText,
Is.EqualTo("INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)"));
Assert.That(command.Parameters, Has.Count.EqualTo(6));
@@ -264,27 +268,29 @@ public void BufferingWebsiteExample()
public void NullPropertyXmlConfig()
{
XmlDocument log4NetConfig = new();
- log4NetConfig.LoadXml(@"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- ");
+ log4NetConfig.LoadXml(
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
XmlConfigurator.Configure(rep, log4NetConfig["log4net"]!);
@@ -294,7 +300,7 @@ public void NullPropertyXmlConfig()
IDbCommand? command = Log4NetCommand.MostRecentInstance;
Assert.That(command, Is.Not.Null);
- IDbDataParameter param = (IDbDataParameter)command!.Parameters["@productId"];
+ IDbDataParameter param = (IDbDataParameter)command.Parameters["@productId"];
Assert.That(param.Value, Is.Not.EqualTo(SystemInfo.NullText));
Assert.That(param.Value, Is.EqualTo(DBNull.Value));
}
@@ -331,7 +337,7 @@ public void NullPropertyProgrammaticConfig()
IDbCommand? command = Log4NetCommand.MostRecentInstance;
Assert.That(command, Is.Not.Null);
- IDbDataParameter param = (IDbDataParameter)command!.Parameters["@productId"];
+ IDbDataParameter param = (IDbDataParameter)command.Parameters["@productId"];
Assert.That(param.Value, Is.Not.EqualTo(SystemInfo.NullText));
Assert.That(param.Value, Is.EqualTo(DBNull.Value));
}
diff --git a/src/log4net.Tests/Appender/AppenderCollectionTest.cs b/src/log4net.Tests/Appender/AppenderCollectionTest.cs
index c0e56daf..1b982e49 100644
--- a/src/log4net.Tests/Appender/AppenderCollectionTest.cs
+++ b/src/log4net.Tests/Appender/AppenderCollectionTest.cs
@@ -38,7 +38,7 @@ public class AppenderCollectionTest
[Test]
public void ToArrayTest()
{
- AppenderCollection appenderCollection = new();
+ AppenderCollection appenderCollection = [];
IAppender appender = new MemoryAppender();
appenderCollection.Add(appender);
@@ -51,7 +51,7 @@ public void ToArrayTest()
[Test]
public void ReadOnlyToArrayTest()
{
- AppenderCollection appenderCollection = new();
+ AppenderCollection appenderCollection = [];
IAppender appender = new MemoryAppender();
appenderCollection.Add(appender);
AppenderCollection readonlyAppenderCollection = AppenderCollection.ReadOnly(appenderCollection);
diff --git a/src/log4net.Tests/Appender/FileAppenderTest.cs b/src/log4net.Tests/Appender/FileAppenderTest.cs
index 35b77383..9cebdcef 100644
--- a/src/log4net.Tests/Appender/FileAppenderTest.cs
+++ b/src/log4net.Tests/Appender/FileAppenderTest.cs
@@ -72,27 +72,28 @@ public void FilenameWithPatternStringTest()
try
{
XmlDocument log4NetConfig = new();
- log4NetConfig.LoadXml("""
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-""");
+ log4NetConfig.LoadXml(
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
XmlConfigurator.Configure(rep, log4NetConfig["log4net"]!);
}
@@ -119,27 +120,28 @@ public void FilenameWithGlobalContextPatternStringTest()
}
XmlDocument log4NetConfig = new();
- log4NetConfig.LoadXml("""
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-""");
+ log4NetConfig.LoadXml(
+ """
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
// latest possible moment to set GlobalContext property used in filename
GlobalContext.Properties["LogName"] = "custom_log_issue_193";
diff --git a/src/log4net.Tests/Appender/RollingFileAppenderTest.cs b/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
index 5e818e03..32463bea 100644
--- a/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
+++ b/src/log4net.Tests/Appender/RollingFileAppenderTest.cs
@@ -32,6 +32,7 @@
using log4net.Util;
using NUnit.Framework;
using System.Globalization;
+using System.Linq;
namespace log4net.Tests.Appender;
@@ -143,19 +144,19 @@ public void TearDown()
/// Finds the number of files that match the base file name,
/// and matches the result against an expected count
///
- private static void VerifyFileCount(int iExpectedCount, bool preserveLogFileNameExtension = false)
+ private static void VerifyFileCount(int expectedCount, bool preserveLogFileNameExtension = false)
{
- List alFiles = GetExistingFiles(FileName, preserveLogFileNameExtension);
- Assert.That(alFiles, Is.Not.Null);
- Assert.That(alFiles, Has.Count.EqualTo(iExpectedCount));
+ List files = GetExistingFiles(FileName, preserveLogFileNameExtension);
+ Assert.That(files, Is.Not.Null);
+ Assert.That(files, Has.Count.EqualTo(expectedCount));
}
///
/// Creates a file with the given number, and the shared base file name
///
- private static void CreateFile(int iFileNumber)
+ private static void CreateFile(int fileNumber)
{
- FileInfo fileInfo = new(MakeFileName(FileName, iFileNumber));
+ FileInfo fileInfo = new(MakeFileName(FileName, fileNumber));
FileStream? fileStream = null;
try
@@ -241,14 +242,14 @@ public void RollingCombinedWithPreserveExtension()
///
private static void DeleteTestFiles()
{
- List alFiles = GetExistingFiles(FileName);
- alFiles.AddRange(GetExistingFiles(FileName, true));
- foreach (string sFile in alFiles)
+ List files = GetExistingFiles(FileName);
+ files.AddRange(GetExistingFiles(FileName, true));
+ foreach (string file in files)
{
try
{
- Debug.WriteLine("Deleting test file " + sFile);
- File.Delete(sFile);
+ Debug.WriteLine("Deleting test file " + file);
+ File.Delete(file);
}
catch (Exception e) when (e is not null)
{
@@ -261,17 +262,17 @@ private static void DeleteTestFiles()
/// Generates a file name associated with the count, using
/// the base file name.
///
- ///
- ///
+ ///
+ ///
///
- private static string MakeFileName(string sBaseFile, int iFileCount)
+ private static string MakeFileName(string baseFile, int fileCount)
{
- if (0 == iFileCount)
+ if (0 == fileCount)
{
- return sBaseFile;
+ return baseFile;
}
- return sBaseFile + "." + iFileCount;
+ return baseFile + "." + fileCount;
}
///
@@ -319,90 +320,51 @@ private RollingFileAppender CreateAppender(FileAppender.LockingModelBase lockMod
/// Used for test purposes, a table of these objects can be used to identify
/// any existing files and their expected length.
///
- public sealed class RollFileEntry
- {
- ///
- /// Default constructor
- ///
- public RollFileEntry()
- { }
-
- ///
- /// Constructor used when the fileInfo and expected length are known
- ///
- public RollFileEntry(string fileName, long fileLength)
- {
- FileName = fileName;
- FileLength = fileLength;
- }
-
- ///
- /// Gets the name of the file
- ///
- public string? FileName { get; }
-
- ///
- /// The expected length of the file
- ///
- public long FileLength { get; }
- }
+ private record RollFileEntry(string FileName, long FileLength);
///
/// Used for table-driven testing. This class holds information that can be used
/// for testing of file rolling.
///
- ///
+ ///
/// A table of entries showing files that should exist and their expected sizes
/// before logging is called
///
- ///
+ ///
/// A table of entries showing files that should exist and their expected sizes
/// after a message is logged
///
- public sealed class RollConditions(IList preLogFileEntries, IList postLogFileEntries)
- {
- ///
- /// A table of entries showing files that should exist and their expected sizes
- /// before logging is called
- ///
- public IList PreLogFileEntries => preLogFileEntries;
-
- ///
- /// A table of entries showing files that should exist and their expected sizes
- /// after a message is logged
- ///
- public IList PostLogFileEntries => postLogFileEntries;
- }
+ private record RollConditions(IList PreLogFileEntries, IList PostLogFileEntries);
- private static void VerifyExistenceAndRemoveFromList(List alExisting,
- string sFileName, FileInfo file, RollFileEntry entry)
+ private static void VerifyExistenceAndRemoveFromList(List existing,
+ string fileName, FileInfo file, RollFileEntry entry)
{
- Assert.That(alExisting, Does.Contain(sFileName), $"filename {sFileName} not found in test directory");
+ Assert.That(existing, Does.Contain(fileName), $"filename {fileName} not found in test directory");
Assert.That(file.Length, Is.EqualTo(entry.FileLength), "file length mismatch");
// Remove this file from the list
- alExisting.Remove(sFileName);
+ existing.Remove(fileName);
}
///
/// Checks that all the expected files exist, and only the expected files. Also
/// verifies the length of all files against the expected length
///
- ///
+ ///
///
- private static void VerifyFileConditions(string sBaseFileName, IList fileEntries)
+ private static void VerifyFileConditions(string baseFileName, IList fileEntries)
{
- List alExisting = GetExistingFiles(sBaseFileName);
+ List existingFiles = GetExistingFiles(baseFileName);
foreach (RollFileEntry rollFile in fileEntries)
{
- string? sFileName = rollFile.FileName;
- Assert.That(sFileName, Is.Not.Null);
- FileInfo file = new(sFileName!);
+ string fileName = rollFile.FileName;
+ Assert.That(fileName, Is.Not.Null);
+ FileInfo file = new(fileName);
if (rollFile.FileLength > 0)
{
- Assert.That(file.Exists, $"filename {sFileName} does not exist");
- VerifyExistenceAndRemoveFromList(alExisting, sFileName!, file, rollFile);
+ Assert.That(file.Exists, $"file {fileName} does not exist");
+ VerifyExistenceAndRemoveFromList(existingFiles, fileName, file, rollFile);
}
else
{
@@ -411,14 +373,14 @@ private static void VerifyFileConditions(string sBaseFileName, IList
@@ -426,51 +388,49 @@ private static void VerifyFileConditions(string sBaseFileName, IList
- ///
+ ///
///
- private static void VerifyPreConditions(string sBaseFileName, RollConditions entry)
- => VerifyFileConditions(sBaseFileName, entry.PreLogFileEntries);
+ private static void VerifyPreConditions(string baseFileName, RollConditions entry)
+ => VerifyFileConditions(baseFileName, entry.PreLogFileEntries);
///
/// Called after logging a message to check that all the expected files exist,
/// and only the expected files. Also verifies the length of all files against
/// the expected length
///
- ///
+ ///
///
- private static void VerifyPostConditions(string sBaseFileName, RollConditions entry)
- => VerifyFileConditions(sBaseFileName, entry.PostLogFileEntries);
+ private static void VerifyPostConditions(string baseFileName, RollConditions entry)
+ => VerifyFileConditions(baseFileName, entry.PostLogFileEntries);
///
/// Logs a message, verifying the expected message counts against the
/// current running totals.
///
- private void LogMessage(string sMessageToLog)
+ private void LogMessage(string messageToLog)
{
Assert.That(_caRoot, Is.Not.Null);
- Assert.That(_messagesLogged++, Is.EqualTo(_caRoot!.Counter));
+ Assert.That(_messagesLogged++, Is.EqualTo(_caRoot.Counter));
Assert.That(_root, Is.Not.Null);
- _root!.Log(Level.Debug, sMessageToLog, null);
+ _root.Log(Level.Debug, messageToLog, null);
Assert.That(_messagesLogged, Is.EqualTo(_caRoot.Counter));
}
///
/// Runs through all table entries, logging messages. Before each message is logged,
- /// pre-conditions are checked to ensure the expected files exist and they are the
+ /// pre-conditions are checked to ensure the expected files exists, and they are the
/// expected size. After logging, verifies the same.
///
- ///
+ ///
///
- ///
- private void RollFromTableEntries(string sBaseFileName, RollConditions[] entries, string sMessageToLog)
+ ///
+ private void RollFromTableEntries(string baseFileName, RollConditions[] entries, string messageToLog)
{
- for (int i = 0; i < entries.Length; i++)
+ foreach (RollConditions entry in entries)
{
- RollConditions entry = entries[i];
-
- VerifyPreConditions(sBaseFileName, entry);
- LogMessage(sMessageToLog);
- VerifyPostConditions(sBaseFileName, entry);
+ VerifyPreConditions(baseFileName, entry);
+ LogMessage(messageToLog);
+ VerifyPostConditions(baseFileName, entry);
}
}
@@ -480,124 +440,95 @@ private void RollFromTableEntries(string sBaseFileName, RollConditions[] entries
/// Returns the number of bytes logged per message, including
/// any newline characters in addition to the message length.
///
- ///
///
- private static int TotalMessageLength(string sMessage) => sMessage.Length + _sNewlineLength;
+ private static int TotalMessageLength(string message) => message.Length + _sNewlineLength;
///
/// Determines how many messages of a fixed length can be logged
/// to a single file before the file rolls.
///
- ///
///
- private static int MessagesPerFile(int iMessageLength)
+ private static int MessagesPerFile(int messageLength)
{
- int iMessagesPerFile = MaximumFileSize / iMessageLength;
+ int messagesPerFile = MaximumFileSize / messageLength;
//
// RollingFileAppender checks for wrap BEFORE logging,
// so we will actually get one more message per file than
// we would otherwise.
//
- if (iMessagesPerFile * iMessageLength < MaximumFileSize)
+ if (messagesPerFile * messageLength < MaximumFileSize)
{
- iMessagesPerFile++;
+ messagesPerFile++;
}
- return iMessagesPerFile;
+ return messagesPerFile;
}
///
- /// Determines the name of the current file
+ /// Current file name is always the base file name when counting. Dates will need a different approach.
///
///
- private static string GetCurrentFile() =>
- // Current file name is always the base file name when
- // counting. Dates will need a different approach
- FileName;
+ private static string GetCurrentFile() => FileName;
///
/// Turns a group of file names into an array of file entries that include the name
/// and a size. This is useful for assigning the properties of backup files, when
/// the length of the files are all the same size due to a fixed message length.
///
- ///
- ///
///
- private static List MakeBackupFileEntriesFromBackupGroup(string sBackupGroup, int iBackupFileLength)
+ private static List MakeBackupFileEntriesFromBackupGroup(
+ string backupGroup,
+ int backupFileLength)
{
- string[] sFiles = sBackupGroup.Split(' ');
-
- List result = [];
-
- for (int i = 0; i < sFiles.Length; i++)
- {
- // Weed out any whitespace entries from the array
- if (sFiles[i].Trim().Length > 0)
- {
- result.Add(new RollFileEntry(sFiles[i], iBackupFileLength));
- }
- }
-
- return result;
+ return backupGroup.Split(' ')
+ .Where(file => file.Trim().Length > 0)
+ .Select(file => new RollFileEntry(file, backupFileLength))
+ .ToList();
}
///
/// Finds the iGroup group in the string (comma separated groups)
///
- ///
- ///
///
- private static string GetBackupGroup(string sBackupGroups, int iGroup)
- {
- string[] sGroups = sBackupGroups.Split(',');
- return sGroups[iGroup];
- }
+ private static string GetBackupGroup(string backupGroups, int group)
+ => backupGroups.Split(',')[group];
///
/// Builds a collection of file entries based on the file names
/// specified in a groups string and the max file size from the
/// stats object
///
- ///
- ///
///
- private static List? MakeBackupFileEntriesForPostCondition(string sBackupGroups, RollingStats stats)
+ private static List? MakeBackupFileEntriesForPostCondition(string backupGroups, RollingStats stats)
{
if (0 == stats.NumberOfFileRolls)
{
return null; // first round has no previous backups
}
- string sGroup = GetBackupGroup(sBackupGroups, stats.NumberOfFileRolls - 1);
- return MakeBackupFileEntriesFromBackupGroup(sGroup, stats.MaximumFileSize);
+ string group = GetBackupGroup(backupGroups, stats.NumberOfFileRolls - 1);
+ return MakeBackupFileEntriesFromBackupGroup(group, stats.MaximumFileSize);
}
-
///
/// This class holds information that is used while we are generating
/// test data sets
///
- public sealed class RollingStats
+ ///
+ /// The length of a message, including any CR/LF characters.
+ /// This length assumes all messages are a fixed length for test purposes.
+ ///
+ /// A count of the number of messages that are logged to each file.
+ private sealed record RollingStats(
+ int TotalMessageLength,
+ int MessagesPerFile)
{
///
/// Number of total bytes a log file can reach.
///
public int MaximumFileSize => TotalMessageLength * MessagesPerFile;
- ///
- /// The length of a message, including any CR/LF characters.
- /// This length assumes all messages are a fixed length for
- /// test purposes.
- ///
- public int TotalMessageLength { get; set; }
-
- ///
- /// A count of the number of messages that are logged to each
- /// file.
- ///
- public int MessagesPerFile { get; set; }
-
///
/// Counts how many messages have been logged to the current file
///
@@ -611,22 +542,12 @@ public sealed class RollingStats
///
/// The stats are used to keep track of progress while we are algorithmically
- /// generating a table of pre/post condition tests for file rolling.
+ /// generating a table of pre- / post-condition tests for file rolling.
///
- ///
+ ///
///
- private static RollingStats InitializeStats(string sTestMessage)
- {
- RollingStats rollingStats = new()
- {
- TotalMessageLength = TotalMessageLength(sTestMessage)
- };
- rollingStats.MessagesPerFile = MessagesPerFile(rollingStats.TotalMessageLength);
- rollingStats.MessagesThisFile = 0;
- rollingStats.NumberOfFileRolls = 0;
-
- return rollingStats;
- }
+ private static RollingStats InitializeStats(string testMessage)
+ => new(TotalMessageLength(testMessage), MessagesPerFile(TotalMessageLength(testMessage)));
///
/// Takes an existing array of RollFileEntry objects, creates a new array one element
@@ -639,13 +560,13 @@ private static RollingStats InitializeStats(string sTestMessage)
///
private static List AddFinalElement(List? existing, RollFileEntry final)
{
- int iLength = 1;
+ int length = 1;
if (existing is not null)
{
- iLength += existing.Count;
+ length += existing.Count;
}
- List combined = new(iLength);
+ List combined = new(length);
if (existing is not null)
{
combined.AddRange(existing);
@@ -656,23 +577,20 @@ private static List AddFinalElement(List? existing
}
///
- /// Generates the pre and post condition arrays from an array of backup files and the
+ /// Generates the pre- and post-condition arrays from an array of backup files and the
/// current file / next file.
///
- private static RollConditions BuildTableEntry(string sBackupFiles,
+ private static RollConditions BuildTableEntry(string backupFiles,
RollConditions? preCondition,
RollFileEntry current,
RollFileEntry currentNext,
RollingStats rollingStats)
{
- List? backupsPost = MakeBackupFileEntriesForPostCondition(sBackupFiles, rollingStats);
+ List? backupsPost = MakeBackupFileEntriesForPostCondition(backupFiles, rollingStats);
List post = AddFinalElement(backupsPost, currentNext);
- if (preCondition is null)
- {
- return new RollConditions(AddFinalElement(null, current), post);
- }
-
- return new RollConditions(preCondition.PostLogFileEntries, post);
+ return preCondition is null
+ ? new(AddFinalElement(null, current), post)
+ : new(preCondition.PostLogFileEntries, post);
}
///
@@ -701,11 +619,8 @@ private static RollFileEntry MoveNextEntry(RollingStats rollingStats, RollFileEn
/// Callback point for the regular expression parser. Turns
/// the number into a file name.
///
- private static string NumberedNameMaker(Match match)
- {
- int iValue = int.Parse(match.Value);
- return MakeFileName(FileName, iValue);
- }
+ private static string NumberedNameMaker(Match match)
+ => MakeFileName(FileName, int.Parse(match.Value));
///
/// Parses a numeric list of files, turning them into file names.
@@ -714,58 +629,58 @@ private static string NumberedNameMaker(Match match)
///
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "SYSLIB1045:Convert to 'GeneratedRegexAttribute'.",
Justification = "only .net8")]
- private static string ConvertToFiles(string sBackupInfo, MatchEvaluator evaluator)
- {
- Regex regex = new(@"\d+");
- return regex.Replace(sBackupInfo, evaluator);
- }
+ private static string ConvertToFiles(string backupInfo, MatchEvaluator evaluator)
+ => Regex.Replace(backupInfo, @"\d+", evaluator);
///
/// Makes test entries used for verifying counted file names
///
- /// A message to log repeatedly
- /// Filename groups used to indicate backup file name progression
+ /// A message to log repeatedly
+ /// Filename groups used to indicate backup file name progression
/// that results after each message is logged
- /// How many times the test message will be repeatedly logged
+ /// How many times the test message will be repeatedly logged
///
- private static RollConditions[] MakeNumericTestEntries(string sTestMessage, string sBackupInfo,
- int iMessagesToLog)
- => MakeTestEntries(sTestMessage, sBackupInfo, iMessagesToLog, NumberedNameMaker);
+ private static RollConditions[] MakeNumericTestEntries(
+ string testMessage,
+ string backupInfo,
+ int messagesToLog)
+ => MakeTestEntries(testMessage, backupInfo, messagesToLog, NumberedNameMaker);
///
/// This routine takes a list of backup file names and a message that will be logged
/// repeatedly, and generates a collection of objects containing pre-condition and
- /// post-condition information. This pre/post information shows the names and expected
+ /// post-condition information. This pre- / post-information shows the names and expected
/// file sizes for all files just before and just after a message is logged.
///
- /// A message to log repeatedly
- /// Filename groups used to indicate backup file name progression
+ /// A message to log repeatedly
+ /// Filename groups used to indicate backup file name progression
/// that results after each message is logged
- /// How many times the test message will be repeatedly logged
+ /// How many times the test message will be repeatedly logged
/// Function that can turn a number into a filename
///
- private static RollConditions[] MakeTestEntries(string sTestMessage,
- string sBackupInfo,
- int iMessagesToLog,
- MatchEvaluator evaluator)
+ private static RollConditions[] MakeTestEntries(
+ string testMessage,
+ string backupInfo,
+ int messagesToLog,
+ MatchEvaluator evaluator)
{
- string sBackupFiles = ConvertToFiles(sBackupInfo, evaluator);
+ string backupFiles = ConvertToFiles(backupInfo, evaluator);
- RollConditions[] table = new RollConditions[iMessagesToLog];
+ RollConditions[] table = new RollConditions[messagesToLog];
- RollingStats rollingStats = InitializeStats(sTestMessage);
+ RollingStats rollingStats = InitializeStats(testMessage);
RollConditions? preCondition = null;
rollingStats.MessagesThisFile = 0;
RollFileEntry currentFile = new(GetCurrentFile(), 0);
- for (int i = 0; i < iMessagesToLog; i++)
+ for (int i = 0; i < messagesToLog; i++)
{
RollFileEntry currentNext = new(
GetCurrentFile(),
(1 + rollingStats.MessagesThisFile) * rollingStats.TotalMessageLength);
- table[i] = BuildTableEntry(sBackupFiles, preCondition, currentFile, currentNext, rollingStats);
+ table[i] = BuildTableEntry(backupFiles, preCondition, currentFile, currentNext, rollingStats);
preCondition = table[i];
//System.Diagnostics.Debug.WriteLine( "Message " + i );
@@ -818,7 +733,7 @@ public void TestRollingCountUpFixedBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = "1, 1 2, 1 2 3, 2 3 4, 3 4 5";
+ const string backupInfo = "1, 1 2, 1 2 3, 2 3 4, 3 4 5";
//
// Count Up
@@ -826,12 +741,12 @@ public void TestRollingCountUpFixedBackups()
_countDirection = +1;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
///
@@ -847,7 +762,7 @@ public void TestRollingCountUpInfiniteBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = "1, 1 2, 1 2 3, 1 2 3 4, 1 2 3 4 5";
+ const string backupInfo = "1, 1 2, 1 2 3, 1 2 3 4, 1 2 3 4 5";
//
// Count Up
@@ -860,12 +775,12 @@ public void TestRollingCountUpInfiniteBackups()
_maxSizeRollBackups = -1;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
///
@@ -880,7 +795,7 @@ public void TestRollingCountUpZeroBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = ", , , , ";
+ const string backupInfo = ", , , , ";
//
// Count Up
@@ -893,12 +808,12 @@ public void TestRollingCountUpZeroBackups()
_maxSizeRollBackups = 0;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
@@ -914,7 +829,7 @@ public void TestRollingCountDownFixedBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = "1, 1 2, 1 2 3, 1 2 3, 1 2 3";
+ const string backupInfo = "1, 1 2, 1 2 3, 1 2 3, 1 2 3";
//
// Count Up
@@ -922,12 +837,12 @@ public void TestRollingCountDownFixedBackups()
_countDirection = -1;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
///
@@ -943,7 +858,7 @@ public void TestRollingCountDownInfiniteBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = "1, 1 2, 1 2 3, 1 2 3 4, 1 2 3 4 5";
+ const string backupInfo = "1, 1 2, 1 2 3, 1 2 3 4, 1 2 3 4 5";
//
// Count Down
@@ -956,12 +871,12 @@ public void TestRollingCountDownInfiniteBackups()
_maxSizeRollBackups = -1;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
///
@@ -976,7 +891,7 @@ public void TestRollingCountDownZeroBackups()
// Oldest to newest when reading in a group left-to-right, so 1 2 3 means 1 is the
// oldest, and 3 is the newest
//
- string sBackupInfo = ", , , , ";
+ const string backupInfo = ", , , , ";
//
// Count Up
@@ -989,12 +904,12 @@ public void TestRollingCountDownZeroBackups()
_maxSizeRollBackups = 0;
//
- // Log 30 messages. This is 5 groups, 6 checks per group ( 0, 100, 200, 300, 400, 500
+ // Log 30 messages. This is 5 groups, 6 checks per group (0, 100, 200, 300, 400, 500)
// bytes for current file as messages are logged.
//
- int iMessagesToLog = 30;
+ const int messagesToLog = 30;
- VerifyRolling(MakeNumericTestEntries(GetTestMessage(), sBackupInfo, iMessagesToLog));
+ VerifyRolling(MakeNumericTestEntries(GetTestMessage(), backupInfo, messagesToLog));
}
///
@@ -1022,13 +937,13 @@ private void ConfigureRootAppender()
///
/// Verifies that the current backup index is detected correctly when initializing
///
- ///
- ///
- ///
- private static void VerifyInitializeRollBackupsFromBaseFile(string sBaseFile,
- List alFiles, int iExpectedCurSizeRollBackups)
- => InitializeAndVerifyExpectedValue(alFiles, sBaseFile, CreateRollingFileAppender("5,0,1"),
- iExpectedCurSizeRollBackups);
+ ///
+ ///
+ ///
+ private static void VerifyInitializeRollBackupsFromBaseFile(string baseFile,
+ List files, int expectedCurSizeRollBackups)
+ => InitializeAndVerifyExpectedValue(files, baseFile, CreateRollingFileAppender("5,0,1"),
+ expectedCurSizeRollBackups);
///
/// Tests that the current backup index is 0 when no
@@ -1037,8 +952,8 @@ private static void VerifyInitializeRollBackupsFromBaseFile(string sBaseFile,
[Test]
public void TestInitializeRollBackups1()
{
- string sBaseFile = "LogFile.log";
- List arrFiles =
+ const string baseFile = "LogFile.log";
+ List files =
[
"junk1",
"junk1.log",
@@ -1047,20 +962,19 @@ public void TestInitializeRollBackups1()
"junk.log.2",
];
- int iExpectedCurSizeRollBackups = 0;
- VerifyInitializeRollBackupsFromBaseFile(sBaseFile, arrFiles, iExpectedCurSizeRollBackups);
+ const int expectedCurSizeRollBackups = 0;
+ VerifyInitializeRollBackupsFromBaseFile(baseFile, files, expectedCurSizeRollBackups);
}
///
/// Verifies that files are detected when the base file is specified
///
- ///
- private static void VerifyInitializeRollBackupsFromBaseFile(string sBaseFile)
+ private static void VerifyInitializeRollBackupsFromBaseFile(string baseFile)
{
- List alFiles = MakeTestDataFromString(sBaseFile, "0,1,2");
+ List files = MakeTestDataFromString(baseFile, "0,1,2");
- int iExpectedCurSizeRollBackups = 2;
- VerifyInitializeRollBackupsFromBaseFile(sBaseFile, alFiles, iExpectedCurSizeRollBackups);
+ const int expectedCurSizeRollBackups = 2;
+ VerifyInitializeRollBackupsFromBaseFile(baseFile, files, expectedCurSizeRollBackups);
}
///
@@ -1069,9 +983,9 @@ private static void VerifyInitializeRollBackupsFromBaseFile(string sBaseFile)
[Test]
public void TestInitializeCountUpFixed()
{
- List alFiles = MakeTestDataFromString("3,4,5");
- int iExpectedValue = 5;
- InitializeAndVerifyExpectedValue(alFiles, FileName, CreateRollingFileAppender("3,0,1"), iExpectedValue);
+ List files = MakeTestDataFromString("3,4,5");
+ const int expectedValue = 5;
+ InitializeAndVerifyExpectedValue(files, FileName, CreateRollingFileAppender("3,0,1"), expectedValue);
}
///
@@ -1080,9 +994,9 @@ public void TestInitializeCountUpFixed()
[Test]
public void TestInitializeCountUpFixed2()
{
- List alFiles = MakeTestDataFromString("0,3");
- int iExpectedValue = 3;
- InitializeAndVerifyExpectedValue(alFiles, FileName, CreateRollingFileAppender("3,0,1"), iExpectedValue);
+ List files = MakeTestDataFromString("0,3");
+ const int expectedValue = 3;
+ InitializeAndVerifyExpectedValue(files, FileName, CreateRollingFileAppender("3,0,1"), expectedValue);
}
///
@@ -1092,9 +1006,9 @@ public void TestInitializeCountUpFixed2()
[Test]
public void TestInitializeCountUpZeroBackups()
{
- List alFiles = MakeTestDataFromString("0,3");
- int iExpectedValue = 0;
- InitializeAndVerifyExpectedValue(alFiles, FileName, CreateRollingFileAppender("0,0,1"), iExpectedValue);
+ List files = MakeTestDataFromString("0,3");
+ const int expectedValue = 0;
+ InitializeAndVerifyExpectedValue(files, FileName, CreateRollingFileAppender("0,0,1"), expectedValue);
}
///
@@ -1104,9 +1018,9 @@ public void TestInitializeCountUpZeroBackups()
[Test]
public void TestInitializeCountDownZeroBackups()
{
- List alFiles = MakeTestDataFromString("0,3");
- int iExpectedValue = 0;
- InitializeAndVerifyExpectedValue(alFiles, FileName, CreateRollingFileAppender("0,0,-1"), iExpectedValue);
+ List files = MakeTestDataFromString("0,3");
+ const int expectedValue = 0;
+ InitializeAndVerifyExpectedValue(files, FileName, CreateRollingFileAppender("0,0,-1"), expectedValue);
}
@@ -1116,8 +1030,8 @@ public void TestInitializeCountDownZeroBackups()
[Test]
public void TestInitializeCountDownFixed()
{
- List alFiles = MakeTestDataFromString("4,5,6");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 0);
+ List files = MakeTestDataFromString("4,5,6");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 0);
}
///
@@ -1126,8 +1040,8 @@ public void TestInitializeCountDownFixed()
[Test]
public void TestInitializeCountDownFixed2()
{
- List alFiles = MakeTestDataFromString("1,5,6");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 1);
+ List files = MakeTestDataFromString("1,5,6");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 1);
}
///
@@ -1136,8 +1050,8 @@ public void TestInitializeCountDownFixed2()
[Test]
public void TestInitializeCountDownFixed3()
{
- List alFiles = MakeTestDataFromString("2,5,6");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 2);
+ List files = MakeTestDataFromString("2,5,6");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 2);
}
///
@@ -1146,8 +1060,8 @@ public void TestInitializeCountDownFixed3()
[Test]
public void TestInitializeCountDownFixed4()
{
- List alFiles = MakeTestDataFromString("3,5,6");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 3);
+ List files = MakeTestDataFromString("3,5,6");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 3);
}
///
@@ -1156,8 +1070,8 @@ public void TestInitializeCountDownFixed4()
[Test]
public void TestInitializeCountDownFixed5()
{
- List alFiles = MakeTestDataFromString("1,2,3");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 3);
+ List files = MakeTestDataFromString("1,2,3");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 3);
}
///
@@ -1166,8 +1080,8 @@ public void TestInitializeCountDownFixed5()
[Test]
public void TestInitializeCountDownFixed6()
{
- List alFiles = MakeTestDataFromString("1,2");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 2);
+ List files = MakeTestDataFromString("1,2");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 2);
}
///
@@ -1176,41 +1090,40 @@ public void TestInitializeCountDownFixed6()
[Test]
public void TestInitializeCountDownFixed7()
{
- List alFiles = MakeTestDataFromString("2,3");
- VerifyInitializeDownFixedExpectedValue(alFiles, FileName, 3);
+ List files = MakeTestDataFromString("2,3");
+ VerifyInitializeDownFixedExpectedValue(files, FileName, 3);
}
- private static void InitializeAndVerifyExpectedValue(List alFiles, string sBaseFile,
- RollingFileAppender rfa, int iExpectedValue)
+ private static void InitializeAndVerifyExpectedValue(List files, string baseFile,
+ RollingFileAppender rfa, int expectedValue)
{
- rfa.InitializeRollBackups(sBaseFile, alFiles);
- Assert.That(rfa.CurrentSizeRollBackups, Is.EqualTo(iExpectedValue));
+ rfa.InitializeRollBackups(baseFile, files);
+ Assert.That(rfa.CurrentSizeRollBackups, Is.EqualTo(expectedValue));
}
///
- /// Tests the count down case, with infinite max backups, to see that
+ /// Tests the count-down case, with infinite max backups, to see that
/// initialization of the rolling file appender results in the expected value
///
- ///
- ///
- ///
- private static void VerifyInitializeDownInfiniteExpectedValue(List alFiles,
- string sBaseFile, int iExpectedValue)
- => InitializeAndVerifyExpectedValue(alFiles, sBaseFile, CreateRollingFileAppender("-1,0,-1"), iExpectedValue);
+ ///
+ ///
+ ///
+ private static void VerifyInitializeDownInfiniteExpectedValue(List files,
+ string baseFile, int expectedValue)
+ => InitializeAndVerifyExpectedValue(files, baseFile, CreateRollingFileAppender("-1,0,-1"), expectedValue);
///
/// Creates a RollingFileAppender with the desired values, where the
/// values are passed as a comma separated string, with 3 parameters,
/// maxSizeRollBackups, curSizeRollBackups, CountDirection
///
- ///
///
- private static RollingFileAppender CreateRollingFileAppender(string sParams)
+ private static RollingFileAppender CreateRollingFileAppender(string parameters)
{
- string[] asParams = sParams.Split(',');
- if (asParams?.Length != 3)
+ string[] asParams = parameters.Split(',');
+ if (asParams.Length != 3)
{
- throw new ArgumentOutOfRangeException(sParams, sParams,
+ throw new ArgumentOutOfRangeException(parameters, parameters,
"Must have 3 comma separated params: MaxSizeRollBackups, CurSizeRollBackups, CountDirection");
}
@@ -1232,8 +1145,8 @@ private static RollingFileAppender CreateRollingFileAppender(string sParams)
[Test]
public void TestInitializeCountDownInfinite()
{
- List alFiles = MakeTestDataFromString("2,3");
- VerifyInitializeDownInfiniteExpectedValue(alFiles, FileName, 3);
+ List files = MakeTestDataFromString("2,3");
+ VerifyInitializeDownInfiniteExpectedValue(files, FileName, 3);
}
///
@@ -1243,8 +1156,8 @@ public void TestInitializeCountDownInfinite()
[Test]
public void TestInitializeCountDownInfinite2()
{
- List alFiles = MakeTestDataFromString("2,3,4,5,6,7,8,9,10");
- VerifyInitializeDownInfiniteExpectedValue(alFiles, FileName, 10);
+ List files = MakeTestDataFromString("2,3,4,5,6,7,8,9,10");
+ VerifyInitializeDownInfiniteExpectedValue(files, FileName, 10);
}
///
@@ -1254,8 +1167,8 @@ public void TestInitializeCountDownInfinite2()
[Test]
public void TestInitializeCountDownInfinite3()
{
- List alFiles = MakeTestDataFromString("9,10,3,4,5,7,9,6,1,2,8");
- VerifyInitializeDownInfiniteExpectedValue(alFiles, FileName, 10);
+ List files = MakeTestDataFromString("9,10,3,4,5,7,9,6,1,2,8");
+ VerifyInitializeDownInfiniteExpectedValue(files, FileName, 10);
}
///
@@ -1265,8 +1178,8 @@ public void TestInitializeCountDownInfinite3()
[Test]
public void TestInitializeCountUpInfinite()
{
- List alFiles = MakeTestDataFromString("2,3");
- VerifyInitializeUpInfiniteExpectedValue(alFiles, FileName, 3);
+ List files = MakeTestDataFromString("2,3");
+ VerifyInitializeUpInfiniteExpectedValue(files, FileName, 3);
}
///
@@ -1276,8 +1189,8 @@ public void TestInitializeCountUpInfinite()
[Test]
public void TestInitializeCountUpInfinite2()
{
- List alFiles = MakeTestDataFromString("2,3,4,5,6,7,8,9,10");
- VerifyInitializeUpInfiniteExpectedValue(alFiles, FileName, 10);
+ List files = MakeTestDataFromString("2,3,4,5,6,7,8,9,10");
+ VerifyInitializeUpInfiniteExpectedValue(files, FileName, 10);
}
///
@@ -1287,8 +1200,8 @@ public void TestInitializeCountUpInfinite2()
[Test]
public void TestInitializeCountUpInfinite3()
{
- List alFiles = MakeTestDataFromString("9,10,3,4,5,7,9,6,1,2,8");
- VerifyInitializeUpInfiniteExpectedValue(alFiles, FileName, 10);
+ List files = MakeTestDataFromString("9,10,3,4,5,7,9,6,1,2,8");
+ VerifyInitializeUpInfiniteExpectedValue(files, FileName, 10);
}
///
@@ -1353,8 +1266,8 @@ private static void DestroyLogger()
private static void AssertFileEquals(string filename, string contents)
{
- string logcont = File.ReadAllText(filename);
- Assert.That(logcont, Is.EqualTo(contents), "Log contents is not what is expected");
+ string logContent = File.ReadAllText(filename);
+ Assert.That(logContent, Is.EqualTo(contents), "Log contents is not what is expected");
File.Delete(filename);
}
@@ -1365,7 +1278,7 @@ private static void AssertFileEquals(string filename, string contents)
public void TestLogOutput()
{
Utils.InconclusiveOnMono();
- string filename = "test_simple.log";
+ const string filename = "test_simple.log";
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.ExclusiveLock(), sh);
log.Log(GetType(), Level.Info, "This is a message", null);
@@ -1373,7 +1286,7 @@ public void TestLogOutput()
DestroyLogger();
AssertFileEquals(filename,
- "This is a message" + Environment.NewLine + "This is a message 2" + Environment.NewLine);
+ "This is a message" + Environment.NewLine + "This is a message 2" + Environment.NewLine);
Assert.That(sh.Message, Is.EqualTo(""), "Unexpected error message");
}
@@ -1383,10 +1296,10 @@ public void TestLogOutput()
[Test]
public void TestExclusiveLockFails()
{
- string filename = "test_exclusive_lock_fails.log";
+ const string filename = "test_exclusive_lock_fails.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.ExclusiveLock(), sh);
@@ -1406,10 +1319,10 @@ public void TestExclusiveLockFails()
public void TestExclusiveLockRecovers()
{
Utils.InconclusiveOnMono();
- string filename = "test_exclusive_lock_recovers.log";
+ const string filename = "test_exclusive_lock_recovers.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.ExclusiveLock(), sh);
@@ -1430,7 +1343,7 @@ public void TestExclusiveLockRecovers()
public void TestExclusiveLockLocks()
{
Utils.InconclusiveOnMono();
- string filename = "test_exclusive_lock_locks.log";
+ const string filename = "test_exclusive_lock_locks.log";
bool locked = false;
SilentErrorHandler sh = new();
@@ -1440,7 +1353,7 @@ public void TestExclusiveLockLocks()
try
{
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
fs.Close();
}
catch (IOException e1)
@@ -1467,10 +1380,10 @@ public void TestExclusiveLockLocks()
public void TestMinimalLockFails()
{
Utils.InconclusiveOnMono();
- string filename = "test_minimal_lock_fails.log";
+ const string filename = "test_minimal_lock_fails.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.MinimalLock(), sh);
@@ -1491,10 +1404,10 @@ public void TestMinimalLockFails()
public void TestMinimalLockRecovers()
{
Utils.InconclusiveOnMono();
- string filename = "test_minimal_lock_recovers.log";
+ const string filename = "test_minimal_lock_recovers.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.MinimalLock(), sh);
@@ -1515,14 +1428,12 @@ public void TestMinimalLockRecovers()
public void TestMinimalLockUnlocks()
{
Utils.InconclusiveOnMono();
- string filename = "test_minimal_lock_unlocks.log";
- bool locked;
+ const string filename = "test_minimal_lock_unlocks.log";
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.MinimalLock(), sh);
log.Log(GetType(), Level.Info, "This is a message", null);
- locked = true;
FileStream fs = new(filename, FileMode.Append, FileAccess.Write, FileShare.None);
fs.Write(Encoding.ASCII.GetBytes("Test" + Environment.NewLine), 0, 4 + Environment.NewLine.Length);
fs.Close();
@@ -1530,7 +1441,6 @@ public void TestMinimalLockUnlocks()
log.Log(GetType(), Level.Info, "This is a message 2", null);
DestroyLogger();
- Assert.That(locked, "File was not locked");
AssertFileEquals(filename,
"This is a message" + Environment.NewLine + "Test" + Environment.NewLine + "This is a message 2" +
Environment.NewLine);
@@ -1544,10 +1454,10 @@ public void TestMinimalLockUnlocks()
public void TestInterProcessLockFails()
{
Utils.InconclusiveOnMono();
- string filename = "test_interprocess_lock_fails.log";
+ const string filename = "test_interprocess_lock_fails.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.InterProcessLock(), sh);
@@ -1568,10 +1478,10 @@ public void TestInterProcessLockFails()
public void TestInterProcessLockRecovers()
{
Utils.InconclusiveOnMono();
- string filename = "test_interprocess_lock_recovers.log";
+ const string filename = "test_interprocess_lock_recovers.log";
FileStream fs = new(filename, FileMode.Create, FileAccess.Write, FileShare.None);
- fs.Write(Encoding.ASCII.GetBytes("Test"), 0, 4);
+ fs.Write("Test"u8.ToArray(), 0, 4);
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.InterProcessLock(), sh);
@@ -1592,14 +1502,12 @@ public void TestInterProcessLockRecovers()
public void TestInterProcessLockUnlocks()
{
Utils.InconclusiveOnMono();
- string filename = "test_interprocess_lock_unlocks.log";
- bool locked;
+ const string filename = "test_interprocess_lock_unlocks.log";
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, new FileAppender.InterProcessLock(), sh);
log.Log(GetType(), Level.Info, "This is a message", null);
- locked = true;
FileStream fs = new(filename, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
fs.Write(Encoding.ASCII.GetBytes("Test" + Environment.NewLine), 0, 4 + Environment.NewLine.Length);
fs.Close();
@@ -1607,7 +1515,6 @@ public void TestInterProcessLockUnlocks()
log.Log(GetType(), Level.Info, "This is a message 2", null);
DestroyLogger();
- Assert.That(locked, "File was not locked");
AssertFileEquals(filename,
"This is a message" + Environment.NewLine + "Test" + Environment.NewLine + "This is a message 2" +
Environment.NewLine);
@@ -1642,7 +1549,7 @@ public void TestInterProcessLockRoll()
[Test]
public void TestDefaultLockingModel()
{
- string filename = "test_default.log";
+ const string filename = "test_default.log";
SilentErrorHandler sh = new();
ILogger log = CreateLogger(filename, null, sh);
@@ -1662,18 +1569,18 @@ public void TestDefaultLockingModel()
/// Tests the count up case, with infinite max backups , to see that
/// initialization of the rolling file appender results in the expected value
///
- private static void VerifyInitializeUpInfiniteExpectedValue(List alFiles,
- string sBaseFile, int iExpectedValue)
- => InitializeAndVerifyExpectedValue(alFiles, sBaseFile, CreateRollingFileAppender("-1,0,1"), iExpectedValue);
+ private static void VerifyInitializeUpInfiniteExpectedValue(List files,
+ string baseFile, int expectedValue)
+ => InitializeAndVerifyExpectedValue(files, baseFile, CreateRollingFileAppender("-1,0,1"), expectedValue);
///
/// Tests the countdown case, with max backups limited to 3, to see that
/// initialization of the rolling file appender results in the expected value
///
- private static void VerifyInitializeDownFixedExpectedValue(List alFiles, string sBaseFile,
- int iExpectedValue)
- => InitializeAndVerifyExpectedValue(alFiles, sBaseFile, CreateRollingFileAppender("3,0,-1"), iExpectedValue);
+ private static void VerifyInitializeDownFixedExpectedValue(List files, string baseFile,
+ int expectedValue)
+ => InitializeAndVerifyExpectedValue(files, baseFile, CreateRollingFileAppender("3,0,-1"), expectedValue);
///
/// Turns a string of comma separated numbers into a collection of filenames
@@ -1682,9 +1589,9 @@ private static void VerifyInitializeDownFixedExpectedValue(List alFiles,
/// Defaults to filename in _fileName variable.
///
///
- /// Comma separated list of numbers for counted file names
- private static List MakeTestDataFromString(string sFileNumbers)
- => MakeTestDataFromString(FileName, sFileNumbers);
+ /// Comma separated list of numbers for counted file names
+ private static List MakeTestDataFromString(string fileNumbers)
+ => MakeTestDataFromString(FileName, fileNumbers);
///
/// Turns a string of comma separated numbers into a collection of filenames
@@ -1693,21 +1600,11 @@ private static List MakeTestDataFromString(string sFileNumbers)
/// Uses the input filename.
///
/// Name of file to combine with numbers when generating counted file names
- /// Comma separated list of numbers for counted file names
+ /// Comma separated list of numbers for counted file names
///
- private static List MakeTestDataFromString(string sFileName, string sFileNumbers)
- {
- List alFiles = [];
-
- string[] sNumbers = sFileNumbers.Split(',');
- foreach (string sNumber in sNumbers)
- {
- int iValue = int.Parse(sNumber.Trim());
- alFiles.Add(MakeFileName(sFileName, iValue));
- }
-
- return alFiles;
- }
+ private static List MakeTestDataFromString(string sFileName, string fileNumbers)
+ => fileNumbers.Split(',').Select(number => int.Parse(number.Trim()))
+ .Select(value => MakeFileName(sFileName, value)).ToList();
///
/// Tests that the current backup index is correctly detected
@@ -1727,36 +1624,31 @@ private static List MakeTestDataFromString(string sFileName, string sFil
/// Makes sure that the initialization can detect the backup
/// number correctly.
///
- private static void VerifyInitializeRollBackups(int iBackups, int iMaxSizeRollBackups)
+ private static void VerifyInitializeRollBackups(int backups, int maxSizeRollBackups)
{
- string sBaseFile = "LogFile.log";
- var arrFiles = new List { "junk1" };
- for (int i = 0; i < iBackups; i++)
+ const string baseFile = "LogFile.log";
+ List arrFiles = ["junk1"];
+ for (int i = 0; i < backups; i++)
{
- arrFiles.Add(MakeFileName(sBaseFile, i));
+ arrFiles.Add(MakeFileName(baseFile, i));
}
RollingFileAppender rfa = new()
{
RollingStyle = RollingFileAppender.RollingMode.Size,
- MaxSizeRollBackups = iMaxSizeRollBackups,
+ MaxSizeRollBackups = maxSizeRollBackups,
CurrentSizeRollBackups = 0
};
- rfa.InitializeRollBackups(sBaseFile, arrFiles);
+ rfa.InitializeRollBackups(baseFile, arrFiles);
// iBackups / Meaning
// 0 = none
// 1 = file.log
// 2 = file.log.1
// 3 = file.log.2
- if (iBackups is 0 or 1)
- {
- Assert.That(rfa.CurrentSizeRollBackups, Is.EqualTo(0));
- }
- else
- {
- Assert.That(rfa.CurrentSizeRollBackups, Is.EqualTo(Math.Min(iBackups - 1, iMaxSizeRollBackups)));
- }
+ Assert.That(rfa.CurrentSizeRollBackups, backups is 0 or 1
+ ? Is.EqualTo(0)
+ : Is.EqualTo(Math.Min(backups - 1, maxSizeRollBackups)));
}
///
@@ -1766,17 +1658,17 @@ private static void VerifyInitializeRollBackups(int iBackups, int iMaxSizeRollBa
[Test]
public void TestInitializeRollBackups4()
{
- const int iMaxRollBackups = 5;
- VerifyInitializeRollBackups(0, iMaxRollBackups);
- VerifyInitializeRollBackups(1, iMaxRollBackups);
- VerifyInitializeRollBackups(2, iMaxRollBackups);
- VerifyInitializeRollBackups(3, iMaxRollBackups);
- VerifyInitializeRollBackups(4, iMaxRollBackups);
- VerifyInitializeRollBackups(5, iMaxRollBackups);
- VerifyInitializeRollBackups(6, iMaxRollBackups);
+ const int maxRollBackups = 5;
+ VerifyInitializeRollBackups(0, maxRollBackups);
+ VerifyInitializeRollBackups(1, maxRollBackups);
+ VerifyInitializeRollBackups(2, maxRollBackups);
+ VerifyInitializeRollBackups(3, maxRollBackups);
+ VerifyInitializeRollBackups(4, maxRollBackups);
+ VerifyInitializeRollBackups(5, maxRollBackups);
+ VerifyInitializeRollBackups(6, maxRollBackups);
// Final we cap out at the max value
- VerifyInitializeRollBackups(7, iMaxRollBackups);
- VerifyInitializeRollBackups(8, iMaxRollBackups);
+ VerifyInitializeRollBackups(7, maxRollBackups);
+ VerifyInitializeRollBackups(8, maxRollBackups);
}
///
@@ -1784,11 +1676,7 @@ public void TestInitializeRollBackups4()
/// when it has not also been initialized with ActivateOptions().
///
[Test]
- public void TestCreateCloseNoActivateOptions()
- {
- var appender = new RollingFileAppender();
- appender.Close();
- }
+ public void TestCreateCloseNoActivateOptions() => new RollingFileAppender().Close();
//
// Helper functions to dig into the appender
diff --git a/src/log4net.Tests/Appender/TelnetAppenderTest.cs b/src/log4net.Tests/Appender/TelnetAppenderTest.cs
index c40134df..48bf970b 100644
--- a/src/log4net.Tests/Appender/TelnetAppenderTest.cs
+++ b/src/log4net.Tests/Appender/TelnetAppenderTest.cs
@@ -50,20 +50,21 @@ public void TelnetTest()
XmlDocument log4NetConfig = new();
int port = 9090;
- log4NetConfig.LoadXml($"""
-
-
-
-
-
-
-
-
-
-
-
-
-""");
+ log4NetConfig.LoadXml(
+ $"""
+
+
+
+
+
+
+
+
+
+
+
+
+ """);
string logId = Guid.NewGuid().ToString();
ILoggerRepository repository = LogManager.CreateRepository(logId);
XmlConfigurator.Configure(repository, log4NetConfig["log4net"]!);
diff --git a/src/log4net.Tests/Appender/TraceAppenderTest.cs b/src/log4net.Tests/Appender/TraceAppenderTest.cs
index 2f889c2b..a8fc41ed 100644
--- a/src/log4net.Tests/Appender/TraceAppenderTest.cs
+++ b/src/log4net.Tests/Appender/TraceAppenderTest.cs
@@ -79,9 +79,8 @@ public void MethodNameCategoryTest()
ILog log = LogManager.GetLogger(rep.Name, GetType());
log.Debug("Message");
- Assert.That(
- categoryTraceListener.Category,
- Is.EqualTo(MethodInfo.GetCurrentMethod()!.Name));
+ Assert.That(categoryTraceListener.Category,
+ Is.EqualTo(MethodBase.GetCurrentMethod()!.Name));
}
}
@@ -92,10 +91,7 @@ public override void Write(string? message)
// empty
}
- public override void WriteLine(string? message)
- {
- Write(message);
- }
+ public override void WriteLine(string? message) => Write(message);
public override void Write(string? message, string? category)
{
diff --git a/src/log4net.Tests/Context/LogicalThreadContextTest.cs b/src/log4net.Tests/Context/LogicalThreadContextTest.cs
index 35eddfaf..17a4941a 100644
--- a/src/log4net.Tests/Context/LogicalThreadContextTest.cs
+++ b/src/log4net.Tests/Context/LogicalThreadContextTest.cs
@@ -319,7 +319,7 @@ static async Task MoreWorkProperties(ILog log, string propertyName)
private static async Task SomeWorkStack(string stackName)
{
- var stringAppender = new StringAppender
+ StringAppender stringAppender = new()
{
Layout = new PatternLayout("%property{" + Utils.PropertyKey + "}")
};
@@ -332,7 +332,7 @@ private static async Task SomeWorkStack(string stackName)
using (LogicalThreadContext.Stacks[Utils.PropertyKey].Push(stackName))
{
log.Info("TestMessage");
- Assert.That(stringAppender.GetString(), Is.EqualTo(string.Format("Outer {0}", stackName)), "Test logical thread stack value set");
+ Assert.That(stringAppender.GetString(), Is.EqualTo($"Outer {stackName}"), "Test logical thread stack value set");
stringAppender.Reset();
await MoreWorkStack(log, "A").ConfigureAwait(false);
diff --git a/src/log4net.Tests/Core/FixingTest.cs b/src/log4net.Tests/Core/FixingTest.cs
index e115ae55..3efe326b 100644
--- a/src/log4net.Tests/Core/FixingTest.cs
+++ b/src/log4net.Tests/Core/FixingTest.cs
@@ -67,7 +67,7 @@ public void All_ShouldContainAllFlags()
// Arrange
// Act
var allFlags = Enum.GetValues(typeof(FixFlags)).Cast()
- .Except(new[] { FixFlags.None })
+ .Except([FixFlags.None])
.ToArray();
// Assert
foreach (var flag in allFlags)
@@ -88,7 +88,7 @@ public void TestUnfixedValues()
loggingEventData.LoggerName,
loggingEventData.Level,
loggingEventData.Message,
- new Exception("This is the exception"));
+ new("This is the exception"));
AssertExpectedLoggingEvent(loggingEvent, loggingEventData);
@@ -107,7 +107,7 @@ public void TestAllFixedValues()
loggingEventData.LoggerName,
loggingEventData.Level,
loggingEventData.Message,
- new Exception("This is the exception"));
+ new("This is the exception"));
AssertExpectedLoggingEvent(loggingEvent, loggingEventData);
@@ -128,7 +128,7 @@ public void TestNoFixedValues()
loggingEventData.LoggerName,
loggingEventData.Level,
loggingEventData.Message,
- new Exception("This is the exception"));
+ new("This is the exception"));
AssertExpectedLoggingEvent(loggingEvent, loggingEventData);
@@ -145,7 +145,7 @@ private static LoggingEventData BuildStandardEventData()
Level = Level.Warn,
Message = "Logging event works",
Domain = "ReallySimpleApp",
- LocationInfo = new LocationInfo(typeof(FixingTest).Name, "Main", "Class1.cs", "29"), //Completely arbitary
+ LocationInfo = new(nameof(FixingTest), "Main", "Class1.cs", "29"), //Completely arbitary
ThreadName = Thread.CurrentThread.Name,
TimeStampUtc = DateTime.UtcNow.Date,
ExceptionString = "Exception occured here",
@@ -161,7 +161,7 @@ private static void AssertExpectedLoggingEvent(LoggingEvent loggingEvent, Loggin
Assert.That(loggingEventData.Identity, Is.Null, "Identity is incorrect");
Assert.That(loggingEventData.Level, Is.EqualTo(Level.Warn), "Level is incorrect");
Assert.That(loggingEvent.LocationInformation, Is.Not.Null);
- Assert.That(loggingEvent.LocationInformation!.MethodName, Is.EqualTo("get_LocationInformation"), "Location Info is incorrect");
+ Assert.That(loggingEvent.LocationInformation.MethodName, Is.EqualTo("get_LocationInformation"), "Location Info is incorrect");
Assert.That(loggingEventData.LoggerName, Is.EqualTo("log4net.Tests.Core.FixingTest"), "LoggerName is incorrect");
Assert.That(loggingEvent.Repository, Is.EqualTo(LogManager.GetRepository(TestRepository)), "Repository is incorrect");
Assert.That(loggingEventData.ThreadName, Is.EqualTo(Thread.CurrentThread.Name), "ThreadName is incorrect");
diff --git a/src/log4net.Tests/Core/LevelMappingTest.cs b/src/log4net.Tests/Core/LevelMappingTest.cs
index 0bcb1ed6..52b25d89 100644
--- a/src/log4net.Tests/Core/LevelMappingTest.cs
+++ b/src/log4net.Tests/Core/LevelMappingTest.cs
@@ -17,7 +17,6 @@
//
#endregion
-using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@@ -80,7 +79,7 @@ public void SortEntriesTest()
List sorted = (List)typeof(LevelMapping)
.GetMethod("SortEntries", BindingFlags.NonPublic | BindingFlags.Instance)!
- .Invoke(mapping, Array.Empty