diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d8a13fe1f5..7151d53a82 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -24,8 +24,6 @@ updates: update-types: ["version-update:semver-major"] - dependency-name: "Microsoft.EntityFrameworkCore" update-types: ["version-update:semver-major"] - - dependency-name: "log4net" - update-types: ["version-update:semver-major"] - dependency-name: "Microting.EntityFrameworkCore.MySql" update-types: ["version-update:semver-major"] diff --git a/.gitignore b/.gitignore index 72db80f119..ecc569a8eb 100644 --- a/.gitignore +++ b/.gitignore @@ -302,6 +302,7 @@ AppVeyor/ # ACEmulator specific files [Cc]onfig.js log4net.config +serilog.json Database/tools/password.txt docker.env docker-compose.yml diff --git a/Source/ACE.Adapter.Tests/ACE.Adapter.Tests.csproj b/Source/ACE.Adapter.Tests/ACE.Adapter.Tests.csproj index bbc91c6c8d..4004796cd3 100644 --- a/Source/ACE.Adapter.Tests/ACE.Adapter.Tests.csproj +++ b/Source/ACE.Adapter.Tests/ACE.Adapter.Tests.csproj @@ -44,8 +44,4 @@ - - - - diff --git a/Source/ACE.Adapter/ACE.Adapter.csproj b/Source/ACE.Adapter/ACE.Adapter.csproj index ca33f4d110..3a421759f8 100644 --- a/Source/ACE.Adapter/ACE.Adapter.csproj +++ b/Source/ACE.Adapter/ACE.Adapter.csproj @@ -34,8 +34,4 @@ - - - - diff --git a/Source/ACE.Common/Logging/LogManager.cs b/Source/ACE.Common/Logging/LogManager.cs index c2533b02b1..972ed9c9e6 100644 --- a/Source/ACE.Common/Logging/LogManager.cs +++ b/Source/ACE.Common/Logging/LogManager.cs @@ -9,15 +9,15 @@ namespace ACE.Common.Logging /// Loggers may be requested at any time - including from static field initializers that run before /// Program.Main - because LoggerFactory.AddProvider wires a new provider into every logger the factory /// has already handed out. Ordering therefore does not matter. - /// Messages logged before a provider has been added are dropped, exactly as log4net dropped them before - /// XmlConfigurator ran. + /// Messages logged before a provider has been added are dropped. ACE.Server adds its Serilog provider at the + /// start of Program.Main. /// public static class LogManager { public static ILoggerFactory Factory { get; } = new LoggerFactory(); /// - /// Category name is the type's full name, matching log4net's logger naming. + /// Category name is the type's full name. Serilog receives it as SourceContext, which MinimumLevel overrides in serilog.json match on. /// public static ILogger GetLogger(Type type) => Factory.CreateLogger(type); diff --git a/Source/ACE.DatLoader.Tests/ACE.DatLoader.Tests.csproj b/Source/ACE.DatLoader.Tests/ACE.DatLoader.Tests.csproj index 1997a15998..9b0c40edb2 100644 --- a/Source/ACE.DatLoader.Tests/ACE.DatLoader.Tests.csproj +++ b/Source/ACE.DatLoader.Tests/ACE.DatLoader.Tests.csproj @@ -44,8 +44,4 @@ - - - - diff --git a/Source/ACE.DatLoader/ACE.DatLoader.csproj b/Source/ACE.DatLoader/ACE.DatLoader.csproj index c9e2672318..b73092ef54 100644 --- a/Source/ACE.DatLoader/ACE.DatLoader.csproj +++ b/Source/ACE.DatLoader/ACE.DatLoader.csproj @@ -31,8 +31,4 @@ - - - - diff --git a/Source/ACE.Database.Tests/ACE.Database.Tests.csproj b/Source/ACE.Database.Tests/ACE.Database.Tests.csproj index a3b243fa5b..65bfaed92b 100644 --- a/Source/ACE.Database.Tests/ACE.Database.Tests.csproj +++ b/Source/ACE.Database.Tests/ACE.Database.Tests.csproj @@ -45,8 +45,4 @@ - - - - diff --git a/Source/ACE.Database/ACE.Database.csproj b/Source/ACE.Database/ACE.Database.csproj index 644afc0859..5c7d55b3a6 100644 --- a/Source/ACE.Database/ACE.Database.csproj +++ b/Source/ACE.Database/ACE.Database.csproj @@ -33,8 +33,4 @@ - - - - diff --git a/Source/ACE.Server.Tests/ACE.Server.Tests.csproj b/Source/ACE.Server.Tests/ACE.Server.Tests.csproj index ddd1109c2f..1dc7671c5c 100644 --- a/Source/ACE.Server.Tests/ACE.Server.Tests.csproj +++ b/Source/ACE.Server.Tests/ACE.Server.Tests.csproj @@ -45,7 +45,8 @@ - + + diff --git a/Source/ACE.Server.Tests/Logging/Log4NetConfigConverterTests.cs b/Source/ACE.Server.Tests/Logging/Log4NetConfigConverterTests.cs new file mode 100644 index 0000000000..861d3e3384 --- /dev/null +++ b/Source/ACE.Server.Tests/Logging/Log4NetConfigConverterTests.cs @@ -0,0 +1,458 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Serilog; +using Serilog.Extensions.Logging; + +using ACE.Server.Logging; + +namespace ACE.Server.Tests.Logging +{ + [TestClass] + public class Log4NetConfigConverterTests + { + private static readonly string TestData = Path.Combine(AppContext.BaseDirectory, "Logging", "TestData"); + + private static readonly JsonDocumentOptions JsonOptions = new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }; + + private static string ReadTestData(string name) => File.ReadAllText(Path.Combine(TestData, name)); + + // ---------------------------------------------------------------- patterns + + [TestMethod] + public void File_pattern_converts_to_the_shipped_file_template() + { + var template = Log4NetConfigConverter.ConvertPattern("%date [%thread] %-5level (%logger) %message%newline", out var warnings); + + Assert.AreEqual("{Timestamp:yyyy-MM-dd HH:mm:ss,fff} [{Thread}] {Level:u3} ({SourceContext}) {Message:lj}{NewLine}{Exception}", template); + Assert.AreEqual(0, warnings.Count); + } + + [TestMethod] + public void Console_pattern_converts_to_the_shipped_console_template() + { + var template = Log4NetConfigConverter.ConvertPattern("%date %-5level: %message%newline", out var warnings); + + Assert.AreEqual("{Timestamp:yyyy-MM-dd HH:mm:ss,fff} {Level:u3}: {Message:lj}{NewLine}{Exception}", template); + Assert.AreEqual(0, warnings.Count); + } + + [TestMethod] + public void Pattern_literals_options_and_case_sensitive_names_convert() + { + var template = Log4NetConfigConverter.ConvertPattern("{x} 100%% %d{HH:mm} %p %P{user} %-20c %exception %n", out var warnings); + + Assert.AreEqual("{{x}} 100% {Timestamp:HH:mm} {Level:u3} {user} {SourceContext,-20} {Exception} {NewLine}", template); + Assert.AreEqual(0, warnings.Count); + } + + [TestMethod] + public void Unsupported_pattern_names_are_dropped_with_a_warning() + { + var template = Log4NetConfigConverter.ConvertPattern("%message (%file:%line)%newline", out var warnings); + + Assert.AreEqual("{Message:lj} (:){NewLine}{Exception}", template); + Assert.AreEqual(2, warnings.Count); + } + + // ---------------------------------------------------------------- shipped configs + + [TestMethod] + public void Converting_the_old_default_config_gives_the_new_default_config() + { + var result = Log4NetConfigConverter.Convert(ReadTestData("log4net.config.example")); + + Assert.AreEqual(Normalize(ReadTestData("serilog.json.example")), Normalize(result.Json)); + Assert.AreEqual(1, result.Warnings.Count, string.Join(Environment.NewLine, result.Warnings)); + StringAssert.Contains(result.Warnings[0], "colours"); + } + + [TestMethod] + public void Converting_the_old_docker_config_gives_the_new_docker_config() + { + var result = Log4NetConfigConverter.Convert(ReadTestData("log4net.config.docker")); + + Assert.AreEqual(Normalize(ReadTestData("serilog.json.docker")), Normalize(result.Json)); + } + + private static readonly Action Scenario = factory => + { + factory.CreateLogger("Packets").LogDebug("packet debug"); + factory.CreateLogger("Packets").LogInformation("packet info"); + factory.CreateLogger("ACE.Server.WorldObjects.Corpse").LogDebug("[CORPSE] corpse made"); + factory.CreateLogger("ACE.Server.Factories.LootGenerationFactory").LogDebug("[LOOT] loot made"); + factory.CreateLogger("ACE.Database.ShardDatabase").LogDebug("[DATABASE] saved"); + factory.CreateLogger("ACE.Server.Managers.HouseManager").LogDebug("house debug"); + factory.CreateLogger("Test").LogDebug("plain debug"); + factory.CreateLogger("Test").LogInformation("info line"); + factory.CreateLogger("Test").LogWarning("warn line"); + factory.CreateLogger("Test").LogError("error line"); + }; + + [TestMethod] + public void Old_and_new_default_configs_route_messages_the_same_way() + { + var converted = Run(Log4NetConfigConverter.Convert(ReadTestData("log4net.config.example")).Json, Scenario); + var shipped = Run(ReadTestData("serilog.json.example"), Scenario); + + var expected = new Dictionary + { + ["console.txt"] = new[] { "INF|packet info", "INF|info line", "WRN|warn line", "ERR|error line" }, + ["ACE_Log.txt"] = new[] { "INF|packet info", "DBG|[CORPSE] corpse made", "DBG|[LOOT] loot made", "DBG|[DATABASE] saved", "DBG|house debug", "DBG|plain debug", "INF|info line", "WRN|warn line", "ERR|error line" }, + }; + + AssertFiles(expected, converted); + AssertFiles(expected, shipped); + } + + [TestMethod] + public void Old_and_new_console_examples_route_messages_the_same_way() + { + var result = Log4NetConfigConverter.Convert(ReadTestData("log4net.config.ConsoleExample")); + var converted = Run(result.Json, Scenario); + var shipped = Run(ReadTestData("serilog.json.ConsoleExample"), Scenario); + + var expected = new Dictionary + { + ["console.txt"] = new[] { "INF|packet info", "DBG|[CORPSE] corpse made", "DBG|[LOOT] loot made", "DBG|house debug", "INF|info line", "WRN|warn line", "ERR|error line" }, + }; + + AssertFiles(expected, converted); + AssertFiles(expected, shipped); + } + + [TestMethod] + public void Old_and_new_files_examples_route_messages_the_same_way() + { + var converted = Run(Log4NetConfigConverter.Convert(ReadTestData("log4net.config.FilesExample")).Json, Scenario); + var shipped = Run(ReadTestData("serilog.json.FilesExample"), Scenario); + + var all = new[] { "DBG|packet debug", "INF|packet info", "DBG|[CORPSE] corpse made", "DBG|[LOOT] loot made", "DBG|[DATABASE] saved", "DBG|house debug", "DBG|plain debug", "INF|info line", "WRN|warn line", "ERR|error line" }; + + var expected = new Dictionary + { + ["ACE_Log.txt"] = all, + ["ACE_Log-INFO.txt"] = new[] { "INF|packet info", "INF|info line", "WRN|warn line", "ERR|error line" }, + ["ACE_Log-WARN.txt"] = new[] { "WRN|warn line", "ERR|error line" }, + ["ACE_Log-CORPSE.txt"] = new[] { "DBG|[CORPSE] corpse made" }, + ["ACE_Log-DATABASE.txt"] = new[] { "DBG|[DATABASE] saved" }, + }; + + AssertFiles(expected, converted); + AssertFiles(expected, shipped); + } + + // ---------------------------------------------------------------- semantics + + private const string Layout = ""; + + [TestMethod] + public void Logger_levels_appenders_and_additivity_follow_the_log4net_hierarchy() + { + var xml = $@" + {Layout} + {Layout} + + + "; + + var files = Run(Log4NetConfigConverter.Convert(xml).Json, factory => + { + factory.CreateLogger("ACE.Server.Network.ClientPacket").LogDebug("net debug"); + factory.CreateLogger("ACE.Server.Network.ClientPacket").LogInformation("net info"); + factory.CreateLogger("ACE.Server.Network").LogInformation("net root info"); + factory.CreateLogger("ACE.Server.NetworkTools").LogInformation("not network"); + factory.CreateLogger("Test").LogDebug("debug"); + factory.CreateLogger("Test").LogTrace("trace"); + }); + + AssertFiles(new Dictionary + { + ["net.txt"] = new[] { "INF|net info", "INF|net root info" }, + ["main.txt"] = new[] { "INF|not network", "DBG|debug" }, + }, files); + } + + [TestMethod] + public void Filter_chains_are_evaluated_in_order_like_log4net() + { + // "secret" is denied first; then anything outside INFO..WARN is denied; what is left is accepted by default + var xml = $@" + + + + + {Layout} + + + "; + + var files = Run(Log4NetConfigConverter.Convert(xml).Json, factory => + { + var log = factory.CreateLogger("Test"); + log.LogDebug("d"); + log.LogInformation("i"); + log.LogInformation("has a secret"); + log.LogWarning("w"); + log.LogError("e"); + }); + + AssertFiles(new Dictionary { ["f.txt"] = new[] { "INF|i", "WRN|w" } }, files); + } + + [TestMethod] + public void LevelRangeFilter_accepts_by_default_so_later_filters_do_not_run() + { + // Checked against log4net 2.0.17: in range is accepted outright unless acceptOnMatch is false + var xml = $@" + + + + + {Layout} + + + + + + {Layout} + + + "; + + var files = Run(Log4NetConfigConverter.Convert(xml).Json, factory => + { + var log = factory.CreateLogger("Test"); + log.LogDebug("d"); + log.LogInformation("i"); + log.LogInformation("has a secret"); + log.LogWarning("w"); + log.LogError("e"); + }); + + AssertFiles(new Dictionary + { + ["default.txt"] = new[] { "INF|i", "INF|has a secret", "WRN|w" }, + ["passon.txt"] = new[] { "INF|i", "WRN|w" }, + }, files); + } + + [TestMethod] + public void A_non_additive_logger_also_hides_its_events_from_its_ancestors_appenders() + { + var xml = $@" + {Layout} + {Layout} + {Layout} + + + + "; + + var files = Run(Log4NetConfigConverter.Convert(xml).Json, factory => + { + factory.CreateLogger("ACE.Server.Network.ClientPacket").LogInformation("net"); + factory.CreateLogger("ACE.Server.Managers.HouseManager").LogInformation("house"); + factory.CreateLogger("ACE.Database").LogInformation("database"); + }); + + AssertFiles(new Dictionary + { + ["net.txt"] = new[] { "INF|net" }, + ["server.txt"] = new[] { "INF|house" }, + ["root.txt"] = new[] { "INF|house", "INF|database" }, + }, files); + } + + [TestMethod] + public void Console_appenders_get_a_theme_that_writes_each_line_once() + { + var xml = $@" + {Layout} + {Layout} + + "; + + var sinks = JsonNode.Parse(Log4NetConfigConverter.Convert(xml).Json)["Serilog"]["WriteTo"].AsArray().Select(s => s["Args"].AsObject()).ToList(); + + Assert.AreEqual(Log4NetConfigConverter.ColouredConsoleTheme, (string)sinks[0]["theme"]); + Assert.AreEqual(Log4NetConfigConverter.PlainConsoleTheme, (string)sinks[1]["theme"]); + } + + [TestMethod] + public void A_date_pattern_that_ends_with_the_extension_moves_it_to_the_path() + { + // log4net wrote logs/ace-2026-11-25.txt; Serilog writes logs/ace-20261125.txt + var xml = $@" + {Layout} + + "; + + var args = JsonNode.Parse(Log4NetConfigConverter.Convert(xml).Json)["Serilog"]["WriteTo"][0]["Args"]; + + Assert.AreEqual("logs/ace-.txt", (string)args["path"]); + Assert.AreEqual("Day", (string)args["rollingInterval"]); + } + + [TestMethod] + public void Unsupported_appenders_are_skipped_with_a_warning() + { + var xml = $@" + + {Layout} + + "; + + var result = Log4NetConfigConverter.Convert(xml); + + Assert.IsTrue(result.Warnings.Any(w => w.Contains("SmtpAppender")), string.Join(Environment.NewLine, result.Warnings)); + Assert.IsTrue(result.Warnings.Any(w => w.Contains("\"Missing\"")), string.Join(Environment.NewLine, result.Warnings)); + + // log4net's default root level is DEBUG + var files = Run(result.Json, factory => + { + factory.CreateLogger("Test").LogTrace("trace"); + factory.CreateLogger("Test").LogDebug("debug"); + }); + + AssertFiles(new Dictionary { ["f.txt"] = new[] { "DBG|debug" } }, files); + } + + [TestMethod] + public void Rolling_settings_follow_the_rolling_style() + { + var xml = $@" + {Layout} + {Layout} + {Layout} + + "; + + var sinks = JsonNode.Parse(Log4NetConfigConverter.Convert(xml).Json)["Serilog"]["WriteTo"].AsArray().Select(s => s["Args"].AsObject()).ToList(); + + Assert.AreEqual("Day", (string)sinks[0]["rollingInterval"]); + Assert.AreEqual(true, (bool)sinks[0]["rollOnFileSizeLimit"]); + Assert.AreEqual(10L * 1024 * 1024, (long)sinks[0]["fileSizeLimitBytes"]); + Assert.IsNull(sinks[0]["retainedFileCountLimit"]); + + Assert.AreEqual("Hour", (string)sinks[1]["rollingInterval"]); + Assert.IsNull(sinks[1]["fileSizeLimitBytes"]); + Assert.IsNull(sinks[1]["retainedFileCountLimit"]); + + Assert.IsNull(sinks[2]["rollingInterval"]); + Assert.AreEqual(5L * 1024 * 1024, (long)sinks[2]["fileSizeLimitBytes"]); + Assert.IsNull(sinks[2]["retainedFileCountLimit"]); + } + + // ---------------------------------------------------------------- helpers + + /// + /// Key order and the order of "Using" don't matter + /// + private static string Normalize(string json) + { + static JsonNode Sort(JsonNode node, string key) + { + switch (node) + { + case JsonObject obj: + var sorted = new JsonObject(); + foreach (var kvp in obj.OrderBy(k => k.Key, StringComparer.Ordinal)) + sorted[kvp.Key] = Sort(kvp.Value, kvp.Key); + return sorted; + case JsonArray array: + var items = array.Select(i => Sort(i, null)).ToList(); + if (key == "Using") + items = items.OrderBy(i => i.ToJsonString(), StringComparer.Ordinal).ToList(); + return new JsonArray(items.ToArray()); + default: + return node?.DeepClone(); + } + } + + return Sort(JsonNode.Parse(json, documentOptions: JsonOptions), null).ToJsonString(new JsonSerializerOptions { WriteIndented = true }); + } + + /// + /// Runs a serilog.json with every sink writing "LEVEL|message" lines into a temporary folder: each File sink to its own + /// file name, and every Console sink to console.txt. Returns the lines per file. + /// + private static Dictionary Run(string json, Action emit) + { + var directory = Path.Combine(Path.GetTempPath(), "ace-serilog-test-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + + try + { + var root = JsonNode.Parse(json, documentOptions: JsonOptions); + Redirect(root, directory); + + var configuration = new ConfigurationBuilder() + .AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(root.ToJsonString()))) + .Build(); + + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + + using (var factory = new LoggerFactory()) + { + factory.AddProvider(new SerilogLoggerProvider(logger, dispose: true)); + emit(factory); + } + + return Directory.GetFiles(directory).ToDictionary(Path.GetFileName, f => File.ReadAllLines(f)); + } + finally + { + Directory.Delete(directory, true); + } + } + + private static void Redirect(JsonNode node, string directory) + { + if (node is JsonArray array) + { + foreach (var item in array) + Redirect(item, directory); + return; + } + + if (node is not JsonObject obj) + return; + + var name = (obj["Name"] as JsonValue)?.GetValue(); + var args = obj["Args"] as JsonObject; + + if ((name == "File" || name == "Console") && args != null) + { + var file = name == "Console" ? "console.txt" : Path.GetFileName((string)args["path"]); + + obj["Name"] = "File"; + args.Remove("standardErrorFromLevel"); + args.Remove("theme"); + args["path"] = Path.Combine(directory, file); + args["shared"] = true; // several sinks may write the same file here + args["outputTemplate"] = "{Level:u3}|{Message:lj}{NewLine}"; + return; + } + + foreach (var kvp in obj.ToList()) + Redirect(kvp.Value, directory); + } + + private static void AssertFiles(Dictionary expected, Dictionary actual) + { + CollectionAssert.AreEquivalent(expected.Keys.ToList(), actual.Keys.ToList(), "files: " + string.Join(", ", actual.Keys)); + + foreach (var kvp in expected) + CollectionAssert.AreEqual(kvp.Value, actual[kvp.Key], $"{kvp.Key}:{Environment.NewLine}{string.Join(Environment.NewLine, actual[kvp.Key])}"); + } + } +} diff --git a/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs b/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs deleted file mode 100644 index a366540962..0000000000 --- a/Source/ACE.Server.Tests/Logging/LogBridgeTests.cs +++ /dev/null @@ -1,136 +0,0 @@ -using System; -using System.Linq; - -using log4net.Appender; -using log4net.Config; - -using Microsoft.Extensions.Logging; -using Microsoft.VisualStudio.TestTools.UnitTesting; - -using ACE.Server.Logging; - -namespace ACE.Server.Tests.Logging -{ - /// - /// Proves standard ILogger calls, routed into log4net by the bridge, render the same text the log4net - /// calls they replaced did: template values, escaped and literal braces, correct levels, exceptions, - /// no formatting at a disabled level, and level checks that follow configuration. Each test uses an - /// isolated log4net repository. - /// - [TestClass] - public class LogBridgeTests - { - private static (ILoggerFactory factory, MemoryAppender appender, log4net.Repository.Hierarchy.Hierarchy repo) Setup(log4net.Core.Level threshold) - { - var repo = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.CreateRepository(Guid.NewGuid().ToString()); - var appender = new MemoryAppender(); - BasicConfigurator.Configure(repo, appender); - repo.Root.Level = threshold; - repo.RaiseConfigurationChanged(EventArgs.Empty); - - var factory = new LoggerFactory(); - factory.AddProvider(new Log4NetBridgeProvider(repo)); - return (factory, appender, repo); - } - - [TestMethod] - public void Template_values_are_rendered_and_escaped_braces_survive() - { - var (factory, appender, _) = Setup(log4net.Core.Level.All); - var log = factory.CreateLogger(typeof(LogBridgeTests)); - - log.LogInformation("hello {World} {{literal}} \"quoted\" 0x{Guid:X8}", "earth", 0xABCu); - - var e = appender.GetEvents().Single(); - Assert.AreEqual("hello earth {literal} \"quoted\" 0x00000ABC", e.RenderedMessage); - Assert.AreEqual(log4net.Core.Level.Info, e.Level); - Assert.AreEqual(typeof(LogBridgeTests).FullName, e.LoggerName, "category must match log4net's logger naming so config entries still apply"); - } - - [TestMethod] - public void Prebuilt_text_passed_as_a_value_is_rendered_literally() - { - var (factory, appender, _) = Setup(log4net.Core.Level.All); - var log = factory.CreateLogger("literal"); - - log.LogInformation("{Message:l}", "hello {world} {0} }{"); - - Assert.AreEqual("hello {world} {0} }{", appender.GetEvents().Single().RenderedMessage); - } - - [TestMethod] - public void Every_level_maps_to_its_log4net_counterpart() - { - var (factory, appender, _) = Setup(log4net.Core.Level.All); - var log = factory.CreateLogger("levels"); - - log.LogDebug("d"); log.LogInformation("i"); log.LogWarning("w"); log.LogError("e"); log.LogCritical("f"); - - var levels = appender.GetEvents().Select(e => e.Level).ToArray(); - CollectionAssert.AreEqual(new[] { log4net.Core.Level.Debug, log4net.Core.Level.Info, log4net.Core.Level.Warn, log4net.Core.Level.Error, log4net.Core.Level.Fatal }, levels); - } - - [TestMethod] - public void Exception_is_carried_as_the_exception() - { - var (factory, appender, _) = Setup(log4net.Core.Level.All); - var log = factory.CreateLogger("ex"); - var ex = new InvalidOperationException("boom"); - - log.LogError(ex, "{Message:l}", ex.Message); - log.LogWarning(ex, "context"); - - var events = appender.GetEvents(); - Assert.AreSame(ex, events[0].ExceptionObject); Assert.AreEqual("boom", events[0].RenderedMessage); - Assert.AreSame(ex, events[1].ExceptionObject); Assert.AreEqual("context", events[1].RenderedMessage); - } - - [TestMethod] - public void Values_are_not_formatted_when_the_level_is_disabled() - { - var (factory, appender, _) = Setup(log4net.Core.Level.Info); - var log = factory.CreateLogger("disabled"); - - log.LogDebug("{Value}", new ThrowsOnToString()); - - Assert.AreEqual(0, appender.GetEvents().Length); - } - - [TestMethod] - public void IsEnabled_follows_the_configured_level() - { - var (factory, _, repo) = Setup(log4net.Core.Level.All); - var log = factory.CreateLogger("enabled"); - Assert.IsTrue(log.IsEnabled(LogLevel.Debug)); - - repo.Root.Level = log4net.Core.Level.Info; - repo.RaiseConfigurationChanged(EventArgs.Empty); - Assert.IsFalse(log.IsEnabled(LogLevel.Debug)); - Assert.IsTrue(log.IsEnabled(LogLevel.Information)); - } - - [TestMethod] - public void Loggers_created_before_the_provider_is_added_still_receive_it() - { - // This is what makes the static-field pattern safe without DI: static initialisers run before - // Main wires providers, and LoggerFactory.AddProvider updates loggers already handed out. - var repo = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.CreateRepository(Guid.NewGuid().ToString()); - var appender = new MemoryAppender(); - BasicConfigurator.Configure(repo, appender); - - var factory = new LoggerFactory(); - var early = factory.CreateLogger("early"); - early.LogInformation("dropped - no provider yet"); - Assert.AreEqual(0, appender.GetEvents().Length); - - factory.AddProvider(new Log4NetBridgeProvider(repo)); - early.LogInformation("delivered"); - Assert.AreEqual("delivered", appender.GetEvents().Single().RenderedMessage); - } - - private sealed class ThrowsOnToString - { - public override string ToString() => throw new InvalidOperationException("formatted while disabled"); - } - } -} diff --git a/Source/ACE.Server.Tests/Logging/SerilogProviderTests.cs b/Source/ACE.Server.Tests/Logging/SerilogProviderTests.cs new file mode 100644 index 0000000000..36971762de --- /dev/null +++ b/Source/ACE.Server.Tests/Logging/SerilogProviderTests.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Extensions.Logging; +using Serilog.Formatting.Display; + +namespace ACE.Server.Tests.Logging +{ + /// + /// ACE logs through Microsoft.Extensions.Logging; these check what reaches Serilog through the provider + /// + [TestClass] + public class SerilogProviderTests + { + private sealed class CollectingSink : ILogEventSink + { + public readonly List Events = new List(); + + public void Emit(LogEvent logEvent) => Events.Add(logEvent); + } + + private static (ILoggerFactory factory, CollectingSink sink) Setup(Action configure = null) + { + var sink = new CollectingSink(); + var configuration = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink); + configure?.Invoke(configuration); + + var factory = new LoggerFactory(); + factory.AddProvider(new SerilogLoggerProvider(configuration.CreateLogger(), dispose: true)); + return (factory, sink); + } + + private static string Render(LogEvent logEvent, string template = "{Message:lj}") + { + var writer = new StringWriter(); + new MessageTemplateTextFormatter(template).Format(logEvent, writer); + return writer.ToString(); + } + + [TestMethod] + public void Template_values_and_format_specifiers_are_rendered_and_escaped_braces_survive() + { + var (factory, sink) = Setup(); + + factory.CreateLogger("Test").LogInformation("{Name} hit 0x{Guid:X8} for {Damage} {{not a hole}}", "Bob", 0x8000_1234u, 1234); + + Assert.AreEqual("Bob hit 0x80001234 for 1234 {not a hole}", Render(sink.Events.Single())); + } + + [TestMethod] + public void Prebuilt_text_passed_as_a_value_is_rendered_literally() + { + var (factory, sink) = Setup(); + + factory.CreateLogger("Test").LogInformation("{Message:l}", "text with {braces} and \"quotes\""); + + Assert.AreEqual("text with {braces} and \"quotes\"", Render(sink.Events.Single())); + } + + [TestMethod] + public void Every_level_maps_to_its_Serilog_counterpart() + { + var (factory, sink) = Setup(); + var log = factory.CreateLogger("Test"); + + log.LogTrace("t"); + log.LogDebug("d"); + log.LogInformation("i"); + log.LogWarning("w"); + log.LogError("e"); + log.LogCritical("c"); + + CollectionAssert.AreEqual( + new[] { LogEventLevel.Verbose, LogEventLevel.Debug, LogEventLevel.Information, LogEventLevel.Warning, LogEventLevel.Error, LogEventLevel.Fatal }, + sink.Events.Select(e => e.Level).ToArray()); + } + + [TestMethod] + public void Exception_is_carried_as_the_exception() + { + var (factory, sink) = Setup(); + var ex = new InvalidOperationException("boom"); + + factory.CreateLogger("Test").LogError(ex, "{Message:l}", ex.Message); + + Assert.AreSame(ex, sink.Events.Single().Exception); + Assert.AreEqual("boom", Render(sink.Events.Single())); + } + + private sealed class CountingToString + { + public int Count; + + public override string ToString() + { + Count++; + return "value"; + } + } + + [TestMethod] + public void Values_are_not_formatted_when_the_level_is_disabled() + { + var (factory, sink) = Setup(c => c.MinimumLevel.Information()); + var log = factory.CreateLogger("Test"); + var value = new CountingToString(); + + Assert.IsFalse(log.IsEnabled(LogLevel.Debug)); + log.LogDebug("{Value}", value); + + Assert.AreEqual(0, sink.Events.Count); + Assert.AreEqual(0, value.Count); + } + + [TestMethod] + public void Category_becomes_SourceContext_and_overrides_apply_to_it() + { + var (factory, sink) = Setup(c => c.MinimumLevel.Override("Packets", LogEventLevel.Information)); + + factory.CreateLogger("Packets").LogDebug("packet debug"); + factory.CreateLogger("Packets").LogInformation("packet info"); + factory.CreateLogger("ACE.Server.Managers.HouseManager").LogDebug("house debug"); + + CollectionAssert.AreEqual(new[] { "packet info", "house debug" }, sink.Events.Select(e => Render(e)).ToArray()); + Assert.AreEqual("\"ACE.Server.Managers.HouseManager\"", sink.Events[1].Properties["SourceContext"].ToString()); + } + + [TestMethod] + public void Loggers_created_before_the_provider_is_added_still_receive_it() + { + // ACE's loggers are static fields, created before Program.Main adds the Serilog provider + var factory = new LoggerFactory(); + var early = factory.CreateLogger("Early"); + + var sink = new CollectingSink(); + factory.AddProvider(new SerilogLoggerProvider(new LoggerConfiguration().WriteTo.Sink(sink).CreateLogger(), dispose: true)); + + early.LogInformation("hello"); + + Assert.AreEqual("hello", Render(sink.Events.Single())); + } + } +} diff --git a/Source/ACE.Server.Tests/Logging/SerilogSetupTests.cs b/Source/ACE.Server.Tests/Logging/SerilogSetupTests.cs new file mode 100644 index 0000000000..d7d5c78351 --- /dev/null +++ b/Source/ACE.Server.Tests/Logging/SerilogSetupTests.cs @@ -0,0 +1,259 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Serilog; +using Serilog.Events; + +using ACE.Server.Logging; + +namespace ACE.Server.Tests.Logging +{ + [TestClass] + public class SerilogSetupTests + { + private static readonly string TestData = Path.Combine(AppContext.BaseDirectory, "Logging", "TestData"); + + private string root, work, exe, container; + + [TestInitialize] + public void Initialize() + { + root = Path.Combine(Path.GetTempPath(), "ace-serilog-setup-" + Guid.NewGuid().ToString("N")); + work = Directory.CreateDirectory(Path.Combine(root, "work")).FullName; + exe = Directory.CreateDirectory(Path.Combine(root, "exe")).FullName; + container = Directory.CreateDirectory(Path.Combine(root, "container")).FullName; + + File.Copy(Path.Combine(TestData, "serilog.json.example"), Path.Combine(exe, "serilog.json.example")); + File.Copy(Path.Combine(TestData, "serilog.json.docker"), Path.Combine(exe, "serilog.json.docker")); + } + + [TestCleanup] + public void Cleanup() + { + Directory.Delete(root, true); + } + + private const string CustomLog4Net = @" + + + "; + + [TestMethod] + public void An_existing_log4net_config_is_converted_when_there_is_no_serilog_json() + { + File.WriteAllText(Path.Combine(exe, "log4net.config"), CustomLog4Net); + var notes = new List(); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, notes); + + Assert.AreEqual(Path.Combine(exe, "serilog.json"), file); + StringAssert.Contains(File.ReadAllText(file), "custom.txt"); + StringAssert.Contains(File.ReadAllText(file), "\"Default\": \"Warning\""); + Assert.IsTrue(notes.Any(n => n.Level == LogLevel.Warning && n.Message.Contains("converted"))); + Assert.IsTrue(File.Exists(Path.Combine(exe, "log4net.config")), "the log4net file is left in place"); + } + + [TestMethod] + public void A_log4net_config_in_the_working_directory_is_converted_too() + { + File.WriteAllText(Path.Combine(work, "log4net.config"), CustomLog4Net); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, new List()); + + StringAssert.Contains(File.ReadAllText(file), "custom.txt"); + } + + [TestMethod] + public void An_existing_serilog_json_wins_over_log4net_config() + { + File.WriteAllText(Path.Combine(exe, "log4net.config"), CustomLog4Net); + File.WriteAllText(Path.Combine(exe, "serilog.json"), "{ \"mine\": true }"); + var notes = new List(); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, notes); + + Assert.AreEqual("{ \"mine\": true }", File.ReadAllText(file)); + Assert.AreEqual(0, notes.Count); + } + + [TestMethod] + public void A_serilog_json_in_the_working_directory_is_used_first() + { + File.WriteAllText(Path.Combine(work, "serilog.json"), "{ }"); + File.WriteAllText(Path.Combine(exe, "serilog.json"), "{ }"); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, new List()); + + Assert.AreEqual(Path.Combine(work, "serilog.json"), file); + } + + [TestMethod] + public void Without_either_file_the_example_is_copied() + { + var notes = new List(); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, notes); + + Assert.AreEqual(File.ReadAllText(Path.Combine(exe, "serilog.json.example")), File.ReadAllText(file)); + Assert.AreEqual(0, notes.Count); + } + + [TestMethod] + public void An_unreadable_log4net_config_falls_back_to_the_example_and_says_so() + { + File.WriteAllText(Path.Combine(exe, "log4net.config"), ""); + var notes = new List(); + + var file = SerilogSetup.ResolveConfigFile(work, exe, false, container, notes); + + Assert.AreEqual(File.ReadAllText(Path.Combine(exe, "serilog.json.example")), File.ReadAllText(file)); + Assert.IsTrue(notes.Any(n => n.Level == LogLevel.Error)); + } + + [TestMethod] + public void In_a_container_a_log4net_config_in_the_config_volume_is_converted_and_kept_there() + { + File.WriteAllText(Path.Combine(container, "log4net.config"), CustomLog4Net); + + var file = SerilogSetup.ResolveConfigFile(work, exe, true, container, new List()); + + Assert.AreEqual(Path.Combine(exe, "serilog.json"), file); + StringAssert.Contains(File.ReadAllText(Path.Combine(container, "serilog.json")), "custom.txt"); + } + + [TestMethod] + public void In_a_container_without_either_file_the_docker_file_is_copied_to_both_places() + { + var file = SerilogSetup.ResolveConfigFile(work, exe, true, container, new List()); + + var docker = File.ReadAllText(Path.Combine(exe, "serilog.json.docker")); + Assert.AreEqual(docker, File.ReadAllText(file)); + Assert.AreEqual(docker, File.ReadAllText(Path.Combine(container, "serilog.json"))); + } + + [TestMethod] + public void In_a_container_the_config_volume_copy_wins() + { + File.WriteAllText(Path.Combine(container, "serilog.json"), "{ \"volume\": true }"); + File.WriteAllText(Path.Combine(exe, "serilog.json"), "{ \"stale\": true }"); + + var file = SerilogSetup.ResolveConfigFile(work, exe, true, container, new List()); + + Assert.AreEqual("{ \"volume\": true }", File.ReadAllText(file)); + } + + [TestMethod] + public void Shipped_example_files_load() + { + foreach (var name in new[] { "serilog.json.example", "serilog.json.docker", "serilog.json.ConsoleExample", "serilog.json.FilesExample" }) + { + var configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(TestData, name)).Build(); + using var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + Assert.IsTrue(logger.IsEnabled(LogEventLevel.Verbose), name); + } + } + + [TestMethod] + public void Relative_file_paths_are_resolved_against_the_executable_folder_like_log4net_did() + { + var json = @"{ ""Serilog"": { ""WriteTo"": [ + { ""Name"": ""Async"", ""Args"": { ""configure"": [ + { ""Name"": ""Console"", ""Args"": { } }, + { ""Name"": ""File"", ""Args"": { ""path"": ""ACE_Log.txt"" } }, + { ""Name"": ""Logger"", ""Args"": { ""configureLogger"": { ""WriteTo"": [ { ""Name"": ""File"", ""Args"": { ""path"": ""logs/chat.txt"" } } ] } } } ] } }, + { ""Name"": ""File"", ""Args"": { ""path"": ""/var/log/ace/abs.txt"" } }, + { ""Name"": ""File"", ""Args"": { ""path"": ""c:\\ACE\\logs\\win.txt"" } } ] } }"; + + var configuration = new ConfigurationBuilder().AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))).Build(); + + SerilogSetup.MakeFilePathsAbsolute(configuration, exe); + + Assert.AreEqual(Path.Combine(exe, "ACE_Log.txt"), configuration["Serilog:WriteTo:0:Args:configure:1:Args:path"]); + Assert.AreEqual(Path.Combine(exe, "logs/chat.txt"), configuration["Serilog:WriteTo:0:Args:configure:2:Args:configureLogger:WriteTo:0:Args:path"]); + Assert.AreEqual("/var/log/ace/abs.txt", configuration["Serilog:WriteTo:1:Args:path"]); + Assert.AreEqual(@"c:\ACE\logs\win.txt", configuration["Serilog:WriteTo:2:Args:path"]); + } + + [TestMethod] + public void The_thread_enricher_writes_the_thread_name_or_its_id_like_log4net_did() + { + // loaded from JSON, the way serilog.json does it + var file = Path.Combine(exe, "thread.txt"); + var json = @"{ ""Serilog"": { ""Using"": [ ""Serilog.Sinks.File"", ""ACE.Server"" ], ""Enrich"": [ ""WithThread"" ], + ""WriteTo"": [ { ""Name"": ""File"", ""Args"": { ""path"": """ + file.Replace("\\", "\\\\") + @""", ""outputTemplate"": ""[{Thread}] {Message:lj}{NewLine}"" } } ] } }"; + + var configuration = new ConfigurationBuilder().AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json))).Build(); + + int unnamedId = 0; + using (var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger()) + { + var named = new Thread(() => logger.Information("named")) { Name = "World Manager" }; + named.Start(); + named.Join(); + + var unnamed = new Thread(() => { unnamedId = Environment.CurrentManagedThreadId; logger.Information("unnamed"); }); + unnamed.Start(); + unnamed.Join(); + } + + CollectionAssert.AreEqual(new[] { "[World Manager] named", $"[{unnamedId}] unnamed" }, File.ReadAllLines(file)); + } + + [TestMethod] + public void SelfLog_prints_one_report_and_then_goes_quiet() + { + var originalError = Console.Error; + var captured = new StringWriter(); + + try + { + Console.SetError(captured); + SerilogSetup.EnableSelfLog(); + + // what a sink does for every message it loses + for (var i = 0; i < 1000; i++) + Serilog.Debugging.SelfLog.WriteLine("unable to enqueue, capacity {0}", 10000); + } + finally + { + Serilog.Debugging.SelfLog.Disable(); + Console.SetError(originalError); + } + + var lines = captured.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); + + Assert.AreEqual(1, lines.Length, captured.ToString()); + StringAssert.Contains(lines[0], "unable to enqueue"); + } + + [TestMethod] + public void Level_changes_in_serilog_json_apply_without_a_restart() + { + var file = Path.Combine(exe, "serilog.json"); + File.WriteAllText(file, "{ \"Serilog\": { \"MinimumLevel\": { \"Default\": \"Information\", \"Override\": { \"Packets\": \"Warning\" } } } }"); + + var configuration = new ConfigurationBuilder().AddJsonFile(file, optional: false, reloadOnChange: true).Build(); + using var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); + var packets = logger.ForContext(Serilog.Core.Constants.SourceContextPropertyName, "Packets"); + + Assert.IsFalse(logger.IsEnabled(LogEventLevel.Debug)); + Assert.IsFalse(packets.IsEnabled(LogEventLevel.Information)); + + File.WriteAllText(file, "{ \"Serilog\": { \"MinimumLevel\": { \"Default\": \"Debug\", \"Override\": { \"Packets\": \"Information\" } } } }"); + + var stopwatch = Stopwatch.StartNew(); + while (!(logger.IsEnabled(LogEventLevel.Debug) && packets.IsEnabled(LogEventLevel.Information)) && stopwatch.Elapsed < TimeSpan.FromSeconds(10)) + Thread.Sleep(50); + + Assert.IsTrue(logger.IsEnabled(LogEventLevel.Debug), "default level reloaded"); + Assert.IsTrue(packets.IsEnabled(LogEventLevel.Information), "override reloaded"); + } + } +} diff --git a/Source/ACE.Server/log4net.config.ConsoleExample b/Source/ACE.Server.Tests/Logging/TestData/log4net.config.ConsoleExample similarity index 100% rename from Source/ACE.Server/log4net.config.ConsoleExample rename to Source/ACE.Server.Tests/Logging/TestData/log4net.config.ConsoleExample diff --git a/Source/ACE.Server/log4net.config.FilesExample b/Source/ACE.Server.Tests/Logging/TestData/log4net.config.FilesExample similarity index 100% rename from Source/ACE.Server/log4net.config.FilesExample rename to Source/ACE.Server.Tests/Logging/TestData/log4net.config.FilesExample diff --git a/Source/ACE.Server/log4net.config.docker b/Source/ACE.Server.Tests/Logging/TestData/log4net.config.docker similarity index 100% rename from Source/ACE.Server/log4net.config.docker rename to Source/ACE.Server.Tests/Logging/TestData/log4net.config.docker diff --git a/Source/ACE.Server/log4net.config.example b/Source/ACE.Server.Tests/Logging/TestData/log4net.config.example similarity index 100% rename from Source/ACE.Server/log4net.config.example rename to Source/ACE.Server.Tests/Logging/TestData/log4net.config.example diff --git a/Source/ACE.Server/ACE.Server.csproj b/Source/ACE.Server/ACE.Server.csproj index b62a2b571a..a0c8480ccf 100644 --- a/Source/ACE.Server/ACE.Server.csproj +++ b/Source/ACE.Server/ACE.Server.csproj @@ -236,9 +236,15 @@ - - + + + + + + + + @@ -266,10 +272,10 @@ PreserveNewest - + PreserveNewest - + PreserveNewest @@ -291,12 +297,8 @@ - - + + - - - - diff --git a/Source/ACE.Server/Entity/Actions/ActionQueue.cs b/Source/ACE.Server/Entity/Actions/ActionQueue.cs index bee6185549..fd2a2a4325 100644 --- a/Source/ACE.Server/Entity/Actions/ActionQueue.cs +++ b/Source/ACE.Server/Entity/Actions/ActionQueue.cs @@ -15,7 +15,7 @@ public class ActionQueue : IActor protected ConcurrentQueue Queue { get; } = new ConcurrentQueue(); #if WRAP_AND_MEASURE_ACT_WITH_STOPWATCH - private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + private static readonly ILogger log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); #endif diff --git a/Source/ACE.Server/Logging/Log4NetBridgeProvider.cs b/Source/ACE.Server/Logging/Log4NetBridgeProvider.cs deleted file mode 100644 index ae94aacd26..0000000000 --- a/Source/ACE.Server/Logging/Log4NetBridgeProvider.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System; - -using log4net.Repository; - -using Microsoft.Extensions.Logging; - -namespace ACE.Server.Logging -{ - /// - /// TEMPORARY BRIDGE. Routes Microsoft.Extensions.Logging into log4net so that log4net.config keeps - /// governing output (levels, appenders, the Packets override) while every call site moves to ILogger. - /// Logger names are the MEL category - the type's full name - so existing <logger name="..."> config - /// entries still match. Delete this file when Serilog replaces log4net. - /// - public sealed class Log4NetBridgeProvider : ILoggerProvider - { - private readonly ILoggerRepository repository; - - public Log4NetBridgeProvider(ILoggerRepository repository) - { - this.repository = repository; - } - - public ILogger CreateLogger(string categoryName) - { - // Same wrapping log4net.LogManager.GetLogger performs internally. - return new Log4NetBridgeLogger(new log4net.Core.LogImpl(repository.GetLogger(categoryName))); - } - - public void Dispose() - { - } - - private sealed class Log4NetBridgeLogger : ILogger - { - private readonly log4net.ILog log; - - public Log4NetBridgeLogger(log4net.ILog log) - { - this.log = log; - } - - public bool IsEnabled(LogLevel logLevel) - { - switch (logLevel) - { - case LogLevel.Trace: - case LogLevel.Debug: return log.IsDebugEnabled; - case LogLevel.Information: return log.IsInfoEnabled; - case LogLevel.Warning: return log.IsWarnEnabled; - case LogLevel.Error: return log.IsErrorEnabled; - case LogLevel.Critical: return log.IsFatalEnabled; - default: return false; - } - } - - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter) - { - if (!IsEnabled(logLevel)) - return; - - var message = formatter(state, exception); - - switch (logLevel) - { - case LogLevel.Trace: - case LogLevel.Debug: log.Debug(message, exception); break; - case LogLevel.Information: log.Info (message, exception); break; - case LogLevel.Warning: log.Warn (message, exception); break; - case LogLevel.Error: log.Error(message, exception); break; - case LogLevel.Critical: log.Fatal(message, exception); break; - } - } - - public IDisposable BeginScope(TState state) => NullScope.Instance; - } - - private sealed class NullScope : IDisposable - { - public static readonly NullScope Instance = new NullScope(); - - public void Dispose() - { - } - } - } -} diff --git a/Source/ACE.Server/Logging/Log4NetConfigConverter.cs b/Source/ACE.Server/Logging/Log4NetConfigConverter.cs new file mode 100644 index 0000000000..8ec1d1e303 --- /dev/null +++ b/Source/ACE.Server/Logging/Log4NetConfigConverter.cs @@ -0,0 +1,940 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.RegularExpressions; +using System.Xml.Linq; + +using Serilog.Expressions; + +namespace ACE.Server.Logging +{ + /// + /// Converts a log4net XML configuration into the equivalent serilog.json (Serilog.Settings.Configuration format). + /// Supported: root and logger levels, console and file appenders, forwarding and async forwarding appenders, + /// appender thresholds, PatternLayout patterns, and the Level/LevelRange/String/Logger/DenyAll filters. + /// Anything else is skipped and reported in . + /// + public static class Log4NetConfigConverter + { + /// + /// Console themes that render a line into a buffer and write it once + /// + public const string ColouredConsoleTheme = "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Sixteen, Serilog.Sinks.Console"; + public const string PlainConsoleTheme = "Serilog.Sinks.SystemConsole.Themes.ConsoleTheme::None, Serilog.Sinks.Console"; + + private static readonly string[] SerilogLevels = { "Verbose", "Debug", "Information", "Warning", "Error", "Fatal" }; + + private const string DefaultLog4NetDateFormat = "yyyy-MM-dd HH:mm:ss,fff"; + + public static Log4NetConversionResult Convert(string log4NetXml) + { + var context = new ConversionContext(); + + var document = XDocument.Parse(log4NetXml); + var root = document.Root?.DescendantsAndSelf().FirstOrDefault(e => Is(e, "log4net")) + ?? throw new FormatException("No element was found."); + + foreach (var appender in root.Elements().Where(e => Is(e, "appender"))) + { + var name = Attribute(appender, "name"); + if (!string.IsNullOrEmpty(name)) + context.Appenders[name] = appender; + } + + // Levels + + var repositoryThreshold = ParseLevel(Attribute(root, "threshold"), context, ""); + + var rootElement = root.Elements().FirstOrDefault(e => Is(e, "root")); + var rootLevel = ParseLevel(LevelOf(rootElement), context, "") ?? new Level(1); // log4net's default root level is DEBUG + + if (repositoryThreshold != null && repositoryThreshold.Value.Index > rootLevel.Index) + rootLevel = repositoryThreshold.Value; + + var overrides = new JsonObject(); + var loggers = root.Elements().Where(e => Is(e, "logger") || Is(e, "category")).ToList(); + + foreach (var logger in loggers) + { + var name = Attribute(logger, "name"); + if (string.IsNullOrEmpty(name)) + continue; + + var level = ParseLevel(LevelOf(logger), context, $""); + if (level != null) + overrides[name] = level.Value.Name; + } + + // Appender paths: every route from or a to a console or file appender + + // An event climbs from its logger towards the root, visiting each ancestor's appenders, and stops after a logger + // with additivity="false". So a logger's appenders see its own events and its descendants', except those from + // below a non-additive logger that sits between them. + var nonAdditiveLoggers = loggers + .Where(l => string.Equals(Attribute(l, "additivity"), "false", StringComparison.OrdinalIgnoreCase)) + .Select(l => Attribute(l, "name")) + .Where(n => !string.IsNullOrEmpty(n)) + .ToList(); + + foreach (var logger in loggers) + { + var name = Attribute(logger, "name"); + if (string.IsNullOrEmpty(name)) + continue; + + var conditions = new List { LoggerCondition(name) }; + conditions.AddRange(nonAdditiveLoggers.Where(n => n.StartsWith(name + ".", StringComparison.Ordinal)).Select(n => Not(LoggerCondition(n)))); + + foreach (var appenderRef in AppenderRefs(logger)) + Walk(appenderRef, new PathState(And(conditions)), context, new HashSet()); + } + + if (rootElement != null) + { + var rootCondition = nonAdditiveLoggers.Count == 0 ? null : And(nonAdditiveLoggers.Select(n => Not(LoggerCondition(n)))); + + foreach (var appenderRef in AppenderRefs(rootElement)) + Walk(appenderRef, new PathState(rootCondition), context, new HashSet()); + } + + if (context.Sinks.Count == 0) + context.Warn("No console or file appender is referenced from or a , so nothing will be logged."); + + // Build the Serilog section + + var asyncSinks = new List(); + var syncSinks = new List(); + + foreach (var sink in context.Sinks.Values) + (sink.IsAsync ? asyncSinks : syncSinks).Add(sink.Build(context)); + + var writeTo = new JsonArray(); + + if (asyncSinks.Count > 0) + { + context.Using.Add("Serilog.Sinks.Async"); + writeTo.Add(new JsonObject { ["Name"] = "Async", ["Args"] = new JsonObject { ["configure"] = new JsonArray(asyncSinks.ToArray()) } }); + } + + foreach (var sink in syncSinks) + writeTo.Add(sink); + + if (context.UsesThread) + context.Using.Add(typeof(ThreadEnricher).Assembly.GetName().Name); + + var minimumLevel = new JsonObject { ["Default"] = rootLevel.Name }; + if (overrides.Count > 0) + minimumLevel["Override"] = overrides; + + var serilog = new JsonObject + { + ["Using"] = new JsonArray(context.Using.OrderBy(u => u, StringComparer.Ordinal).Select(u => (JsonNode)u).ToArray()), + ["MinimumLevel"] = minimumLevel, + }; + + if (context.UsesThread) + serilog["Enrich"] = new JsonArray(nameof(ThreadEnricherExtensions.WithThread)); + + serilog["WriteTo"] = writeTo; + + var json = new JsonObject { ["Serilog"] = serilog }.ToJsonString(new JsonSerializerOptions + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }); + + return new Log4NetConversionResult(json, context.Warnings); + } + + // ---------------------------------------------------------------- appender graph + + private static void Walk(string appenderName, PathState path, ConversionContext context, HashSet visited) + { + if (!context.Appenders.TryGetValue(appenderName, out var appender)) + { + context.Warn($"appender-ref \"{appenderName}\" does not match any ; skipped."); + return; + } + + if (!visited.Add(appenderName)) + { + context.Warn($"Appender \"{appenderName}\" forwards to itself; the loop was skipped."); + return; + } + + var type = ShortTypeName(Attribute(appender, "type")); + var kind = KindOf(type); + + if (kind == AppenderKind.Unsupported) + { + context.Warn($"Appender \"{appenderName}\" ({Attribute(appender, "type")}) has no Serilog equivalent here; skipped."); + return; + } + + // threshold and filters apply to everything passing through this appender, forwarding or not + var threshold = ParseLevel(Param(appender, "threshold"), context, $"appender \"{appenderName}\" threshold"); + if (threshold?.IsOff == true) + return; + + var stage = path.Then(threshold, FilterExpression(appender, appenderName, context), kind == AppenderKind.AsyncForwarding); + + if (kind == AppenderKind.Forwarding || kind == AppenderKind.AsyncForwarding) + { + if (type.StartsWith("Buffering", StringComparison.OrdinalIgnoreCase)) + context.Warn($"Appender \"{appenderName}\" ({type}) is converted as a plain forwarder; its buffering and trigger settings are not carried over."); + + foreach (var appenderRef in AppenderRefs(appender)) + Walk(appenderRef, stage, context, new HashSet(visited)); + + return; + } + + if (!context.Sinks.TryGetValue(appenderName, out var sink)) + { + sink = new SinkDefinition(appenderName, appender, kind); + context.Sinks[appenderName] = sink; + } + + sink.Paths.Add(stage); + } + + private enum AppenderKind { Unsupported, Console, File, Forwarding, AsyncForwarding } + + private static AppenderKind KindOf(string type) + { + switch (type.ToLowerInvariant()) + { + case "consoleappender": + case "coloredconsoleappender": + case "managedcoloredconsoleappender": + case "ansicolorterminalappender": + return AppenderKind.Console; + + case "fileappender": + case "rollingfileappender": + return AppenderKind.File; + + case "forwardingappender": + case "bufferingforwardingappender": + return AppenderKind.Forwarding; + + case "asyncforwardingappender": // Log4Net.Async + case "parallelforwardingappender": // Log4Net.Async + case "asyncappender": + return AppenderKind.AsyncForwarding; + + default: + return AppenderKind.Unsupported; + } + } + + private sealed class PathState + { + public readonly Level? MinLevel; + public readonly List Conditions; + public readonly bool IsAsync; + + public PathState(string condition) + { + Conditions = new List(); + if (condition != null) + Conditions.Add(condition); + } + + private PathState(Level? minLevel, List conditions, bool isAsync) + { + MinLevel = minLevel; + Conditions = conditions; + IsAsync = isAsync; + } + + public PathState Then(Level? threshold, string filter, bool isAsync) + { + var minLevel = MinLevel; + if (threshold != null && (minLevel == null || threshold.Value.Index > minLevel.Value.Index)) + minLevel = threshold; + + var conditions = new List(Conditions); + if (filter != null) + conditions.Add(filter); + + return new PathState(minLevel, conditions, IsAsync || isAsync); + } + + /// + /// The path as one expression, including its level threshold + /// + public string ToExpression() + { + var parts = new List(); + if (MinLevel != null && MinLevel.Value.Index > 0) + parts.Add(LevelAtLeast(MinLevel.Value)); + parts.AddRange(Conditions); + return parts.Count == 0 ? null : And(parts); + } + } + + private sealed class SinkDefinition + { + private readonly string name; + private readonly XElement appender; + private readonly AppenderKind kind; + + public readonly List Paths = new List(); + + public SinkDefinition(string name, XElement appender, AppenderKind kind) + { + this.name = name; + this.appender = appender; + this.kind = kind; + } + + public bool IsAsync => Paths.Any(p => p.IsAsync); + + public JsonObject Build(ConversionContext context) + { + var args = kind == AppenderKind.Console ? ConsoleArgs(context) : FileArgs(context); + + args["outputTemplate"] = ConvertLayout(appender, name, context); + + string filter; + + if (Paths.Count == 1) + { + // a single route keeps its threshold as the sink's own minimum level, which reads more naturally + var path = Paths[0]; + if (path.MinLevel != null && path.MinLevel.Value.Index > 0) + args["restrictedToMinimumLevel"] = path.MinLevel.Value.Name; + filter = path.Conditions.Count == 0 ? null : And(path.Conditions); + } + else + { + // several routes reach the same appender: log4net writes each event once per accepting route, + // Serilog writes it once if any route accepts it + var routes = Paths.Select(p => p.ToExpression()).ToList(); + filter = routes.Any(r => r == null) ? null : Or(routes); + + context.Warn($"Appender \"{name}\" is reached by {Paths.Count} routes. log4net wrote a message once per route that accepted it; Serilog writes it once."); + } + + var sink = new JsonObject + { + ["Name"] = kind == AppenderKind.Console ? "Console" : "File", + ["Args"] = args, + }; + + context.Using.Add(kind == AppenderKind.Console ? "Serilog.Sinks.Console" : "Serilog.Sinks.File"); + + if (filter == null) + return sink; + + if (!SerilogExpression.TryCompile(filter, out _, out var error)) + throw new FormatException($"The filters of appender \"{name}\" produced an expression Serilog cannot read ({error}): {filter}"); + + context.Using.Add("Serilog.Expressions"); + + if (!IsAsync && filter.Contains("@m", StringComparison.Ordinal)) + context.Warn($"Appender \"{name}\" filters on message text and is not behind an async appender. Serilog builds the message text for every message such a filter checks, on the thread that logged it. Moving it inside the \"Async\" sink in serilog.json takes that work off the game threads."); + + return new JsonObject + { + ["Name"] = "Logger", + ["Args"] = new JsonObject + { + ["configureLogger"] = new JsonObject + { + ["Filter"] = new JsonArray(new JsonObject + { + ["Name"] = "ByIncludingOnly", + ["Args"] = new JsonObject { ["expression"] = filter }, + }), + ["WriteTo"] = new JsonArray(sink), + }, + }, + }; + } + + private JsonObject ConsoleArgs(ConversionContext context) + { + var args = new JsonObject(); + + var target = Param(appender, "target"); + if (target != null && target.Contains("Error", StringComparison.OrdinalIgnoreCase)) + args["standardErrorFromLevel"] = "Verbose"; + + // Both themes are written as one buffered write per line. Serilog's default theme instead writes every part of + // the line separately with a colour change each time, which is several times slower than log4net was. + var type = ShortTypeName(Attribute(appender, "type")); + var coloured = !type.Equals("ConsoleAppender", StringComparison.OrdinalIgnoreCase); + + args["theme"] = coloured ? ColouredConsoleTheme : PlainConsoleTheme; + + if (appender.Elements().Any(e => Is(e, "mapping"))) + context.Warn($"Appender \"{name}\": per-level console colours are not converted. log4net coloured the whole line by level; Serilog's console theme colours the level and the values."); + + return args; + } + + private JsonObject FileArgs(ConversionContext context) + { + var args = new JsonObject(); + + var path = Param(appender, "file"); + if (string.IsNullOrWhiteSpace(path)) + { + path = $"{name}.txt"; + context.Warn($"Appender \"{name}\" has no file; using \"{path}\"."); + } + else if (path.Contains('%') || path.Contains("${", StringComparison.Ordinal)) + { + var cleaned = Regex.Replace(path, @"%[a-zA-Z]+(\{[^}]*\})?|\$\{[^}]*\}", ""); + context.Warn($"Appender \"{name}\": the file name pattern \"{path}\" cannot be converted; using \"{cleaned}\"."); + path = cleaned; + } + + args["path"] = path; + + var type = ShortTypeName(Attribute(appender, "type")); + var isRolling = type.Equals("RollingFileAppender", StringComparison.OrdinalIgnoreCase); + + if (string.Equals(Param(appender, "appendToFile"), "false", StringComparison.OrdinalIgnoreCase)) + context.Warn($"Appender \"{name}\": appendToFile=false is not supported; Serilog always appends to an existing file."); + + var lockingModel = appender.Elements().FirstOrDefault(e => Is(e, "lockingModel")); + var lockingType = ShortTypeName(lockingModel == null ? null : Attribute(lockingModel, "type")); + if (lockingType.Contains("MinimalLock", StringComparison.OrdinalIgnoreCase) || lockingType.Contains("InterProcessLock", StringComparison.OrdinalIgnoreCase)) + args["shared"] = true; + + if (string.Equals(Param(appender, "immediateFlush"), "false", StringComparison.OrdinalIgnoreCase)) + args["buffered"] = true; + + if (!isRolling) + { + args["fileSizeLimitBytes"] = null; // a plain FileAppender never stops writing + return args; + } + + var style = (Param(appender, "rollingStyle") ?? "Composite").Trim(); + + var bySize = style.Equals("Size", StringComparison.OrdinalIgnoreCase) || style.Equals("Composite", StringComparison.OrdinalIgnoreCase) || style.Equals("Once", StringComparison.OrdinalIgnoreCase); + var byDate = style.Equals("Date", StringComparison.OrdinalIgnoreCase) || style.Equals("Composite", StringComparison.OrdinalIgnoreCase); + + if (style.Equals("Once", StringComparison.OrdinalIgnoreCase)) + context.Warn($"Appender \"{name}\": rollingStyle Once (a new file per start) has no Serilog equivalent; rolling by size instead."); + + if (byDate) + { + var datePattern = Param(appender, "datePattern") ?? ".yyyy-MM-dd"; + + args["rollingInterval"] = RollingInterval(datePattern); + + // log4net put the date after the file name, so a pattern such as yyyy-MM-dd'.txt' also supplied the extension. + // Serilog puts the date before the extension, so the extension has to be on the path. + var extension = Regex.Match(datePattern, @"'(\.[A-Za-z0-9]+)'\s*$"); + var fileName = path.Substring(path.LastIndexOfAny(new[] { '/', '\\' }) + 1); + + if (extension.Success && !fileName.Contains('.')) + args["path"] = path + extension.Groups[1].Value; + } + + if (bySize) + { + args["rollOnFileSizeLimit"] = true; + args["fileSizeLimitBytes"] = ParseFileSize(Param(appender, "maximumFileSize") ?? Param(appender, "maxFileSize"), name, context); + } + else + args["fileSizeLimitBytes"] = null; + + var backups = Param(appender, "maxSizeRollBackups"); + if (bySize && !byDate) + { + var count = int.TryParse(backups, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0; // log4net default: 0 backups + args["retainedFileCountLimit"] = count < 0 ? null : count + 1; // Serilog counts the current file too + } + else + args["retainedFileCountLimit"] = null; // log4net never deletes date-rolled files + + return args; + } + } + + private static string RollingInterval(string datePattern) + { + // characters inside quotes are literals in a .NET date pattern + var pattern = Regex.Replace(datePattern, "'[^']*'", ""); + + if (pattern.Contains("mm", StringComparison.Ordinal)) + return "Minute"; + if (pattern.Contains("HH", StringComparison.Ordinal) || pattern.Contains("hh", StringComparison.Ordinal)) + return "Hour"; + if (pattern.Contains("dd", StringComparison.Ordinal)) + return "Day"; + if (pattern.Contains("MM", StringComparison.Ordinal)) + return "Month"; + return "Year"; + } + + private static long ParseFileSize(string value, string appenderName, ConversionContext context) + { + const long log4NetDefault = 10L * 1024 * 1024; + + if (string.IsNullOrWhiteSpace(value)) + return log4NetDefault; + + var match = Regex.Match(value.Trim(), @"^(\d+)\s*(KB|MB|GB)?$", RegexOptions.IgnoreCase); + if (!match.Success) + { + context.Warn($"Appender \"{appenderName}\": maximumFileSize \"{value}\" was not understood; using 10MB."); + return log4NetDefault; + } + + var size = long.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture); + return match.Groups[2].Value.ToUpperInvariant() switch + { + "KB" => size * 1024, + "MB" => size * 1024 * 1024, + "GB" => size * 1024 * 1024 * 1024, + _ => size, + }; + } + + // ---------------------------------------------------------------- layouts + + private static string ConvertLayout(XElement appender, string appenderName, ConversionContext context) + { + var layout = appender.Elements().FirstOrDefault(e => Is(e, "layout")); + string pattern; + + if (layout == null) + pattern = "%message%newline"; + else + { + var layoutType = ShortTypeName(Attribute(layout, "type")); + + if (layoutType.Equals("SimpleLayout", StringComparison.OrdinalIgnoreCase)) + pattern = "%level - %message%newline"; + else if (layoutType.StartsWith("PatternLayout", StringComparison.OrdinalIgnoreCase)) + pattern = Param(layout, "conversionPattern") ?? Attribute(layout, "value") ?? "%message%newline"; + else + { + context.Warn($"Appender \"{appenderName}\": layout {Attribute(layout, "type")} is not supported; using a default message template."); + pattern = "%date [%thread] %-5level %logger - %message%newline"; + } + } + + return ConvertPattern(pattern, appenderName, context); + } + + private static readonly Regex PatternToken = new Regex(@"%(?-?\d+)?(?:\.(?\d+))?(?[a-zA-Z]+)(?:\{(?