From 0b4e878d0056990cf6924562070143334cced8f0 Mon Sep 17 00:00:00 2001 From: lodicolo Date: Mon, 27 Jan 2025 21:00:10 -0500 Subject: [PATCH] fix(2512): Properly add guilds to DB, correct DB logging (#2514) --- Intersect.Server.Core/Core/Bootstrapper.cs | 1 - .../Database/DatabaseTypeMigrationService.cs | 2 - Intersect.Server.Core/Database/DbInterface.cs | 75 ++++++++++--------- .../Database/IntersectDbContext.cs | 17 +---- .../Database/IntersectLoggerFactory.cs | 49 ------------ .../Database/PlayerData/Players/Guild.cs | 5 ++ 6 files changed, 49 insertions(+), 100 deletions(-) delete mode 100644 Intersect.Server.Core/Database/IntersectLoggerFactory.cs diff --git a/Intersect.Server.Core/Core/Bootstrapper.cs b/Intersect.Server.Core/Core/Bootstrapper.cs index e9c2b2ed00..11d92b7a84 100644 --- a/Intersect.Server.Core/Core/Bootstrapper.cs +++ b/Intersect.Server.Core/Core/Bootstrapper.cs @@ -232,7 +232,6 @@ private static bool PreContextSetup(params string[] args) } } - DbInterface.InitializeDbLoggers(); DbInterface.CheckDirectories(); PrintIntroduction(); diff --git a/Intersect.Server.Core/Database/DatabaseTypeMigrationService.cs b/Intersect.Server.Core/Database/DatabaseTypeMigrationService.cs index cef78bcdb2..602fbba95d 100644 --- a/Intersect.Server.Core/Database/DatabaseTypeMigrationService.cs +++ b/Intersect.Server.Core/Database/DatabaseTypeMigrationService.cs @@ -209,14 +209,12 @@ PropertyInfo dbSetInfo await using var fromContext = IntersectDbContext.Create(fromOptions with { DisableAutoInclude = true, - LoggerFactory = new IntersectLoggerFactory(typeof(TContext).Name), }); await using var toContext = IntersectDbContext.Create(toOptions with { DisableAutoInclude = true, EnableDetailedErrors = true, EnableSensitiveDataLogging = true, - LoggerFactory = new IntersectLoggerFactory(typeof(TContext).Name), }); if (dbSetInfo.GetValue(fromContext) is not DbSet fromDbSet) diff --git a/Intersect.Server.Core/Database/DbInterface.cs b/Intersect.Server.Core/Database/DbInterface.cs index 5bcce6bfe1..a0b0b3425b 100644 --- a/Intersect.Server.Core/Database/DbInterface.cs +++ b/Intersect.Server.Core/Database/DbInterface.cs @@ -33,6 +33,9 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MySqlConnector; +using Serilog; +using Serilog.Events; +using Serilog.Extensions.Logging; namespace Intersect.Server.Database; @@ -60,10 +63,6 @@ public static partial class DbInterface private static string PlayersDbFilename => Path.Combine(ServerContext.ResourceDirectory, "playerdata.db"); - private static ILogger _gameDatabaseLogger { get; set; } - - private static ILogger _playerDatabaseLogger { get; set; } - public static Dictionary ServerVariableEventTextLookup = new(); public static Dictionary PlayerVariableEventTextLookup = new(); @@ -93,9 +92,7 @@ public static GameContext CreateGameContext( ExplicitLoad = explicitLoad, KillServerOnConcurrencyException = Options.Instance.GameDatabase.KillServerOnConcurrencyException, LazyLoading = lazyLoading, -#if DEBUG - LoggerFactory = new IntersectLoggerFactory(nameof(GameContext)), -#endif + LoggerFactory = CreateLoggerFactory(Options.Instance.GameDatabase), QueryTrackingBehavior = queryTrackingBehavior, ReadOnly = readOnly, }); @@ -117,9 +114,7 @@ internal static LoggingContext CreateLoggingContext( ExplicitLoad = explicitLoad, KillServerOnConcurrencyException = Options.Instance.LoggingDatabase.KillServerOnConcurrencyException, LazyLoading = lazyLoading, -#if DEBUG - LoggerFactory = new IntersectLoggerFactory(nameof(LoggingContext)), -#endif + LoggerFactory = CreateLoggerFactory(Options.Instance.LoggingDatabase), QueryTrackingBehavior = queryTrackingBehavior, ReadOnly = readOnly, }); @@ -146,26 +141,11 @@ public static PlayerContext CreatePlayerContext( ExplicitLoad = explicitLoad, KillServerOnConcurrencyException = Options.Instance.PlayerDatabase.KillServerOnConcurrencyException, LazyLoading = lazyLoading, -#if DEBUG - LoggerFactory = new IntersectLoggerFactory(nameof(PlayerContext)), -#endif + LoggerFactory = CreateLoggerFactory(Options.Instance.PlayerDatabase), QueryTrackingBehavior = queryTrackingBehavior, ReadOnly = readOnly, }); - public static void InitializeDbLoggers() - { - if (Options.Instance.GameDatabase.LogLevel > LogLevel.None) - { - _gameDatabaseLogger = new IntersectLoggerFactory(nameof(GameContext)).CreateLogger(); - } - - if (Options.Instance.PlayerDatabase.LogLevel > LogLevel.None) - { - _playerDatabaseLogger = new IntersectLoggerFactory(nameof(PlayerContext)).CreateLogger(); - } - } - //Check Directories public static void CheckDirectories() { @@ -249,6 +229,24 @@ private static void ProcessMigrations(TContext context) context.OnSchemaMigrationsProcessed(processedSchemaMigrations.ToArray()); } + internal static ILoggerFactory CreateLoggerFactory(DatabaseOptions databaseOptions) + where TDBContext : IntersectDbContext + { + var contextName = typeof(TDBContext).Name; + var configuration = new LoggerConfiguration() + .Enrich.FromLogContext() + .MinimumLevel.Is(LevelConvert.ToSerilogLevel(databaseOptions.LogLevel)) + .WriteTo.Console(restrictedToMinimumLevel: Debugger.IsAttached ? LogEventLevel.Warning : LogEventLevel.Error) + .WriteTo.File(path: $"logs/db-{contextName}.log").WriteTo.File( + path: $"logs/db-errors-{contextName}.log", + restrictedToMinimumLevel: LogEventLevel.Error, + rollOnFileSizeLimit: true, + retainedFileTimeLimit: TimeSpan.FromDays(30) + ); + + return new SerilogLoggerFactory(configuration.CreateLogger()); + } + private static bool EnsureUpdated(IServerContext serverContext) { var gameDatabaseOptions = Options.Instance.GameDatabase; @@ -262,7 +260,7 @@ private static bool EnsureUpdated(IServerContext serverContext) DatabaseType = gameDatabaseOptions.Type, EnableDetailedErrors = true, EnableSensitiveDataLogging = true, - LoggerFactory = new IntersectLoggerFactory(nameof(GameContext)), + LoggerFactory = CreateLoggerFactory(gameDatabaseOptions), }); var playerDatabaseOptions = Options.Instance.PlayerDatabase; @@ -276,7 +274,7 @@ private static bool EnsureUpdated(IServerContext serverContext) DatabaseType = playerDatabaseOptions.Type, EnableDetailedErrors = true, EnableSensitiveDataLogging = true, - LoggerFactory = new IntersectLoggerFactory(nameof(PlayerContext)), + LoggerFactory = CreateLoggerFactory(playerDatabaseOptions), }); var loggingDatabaseOptions = Options.Instance.LoggingDatabase; @@ -290,7 +288,7 @@ private static bool EnsureUpdated(IServerContext serverContext) DatabaseType = loggingDatabaseOptions.Type, EnableDetailedErrors = true, EnableSensitiveDataLogging = true, - LoggerFactory = new IntersectLoggerFactory(nameof(LoggingContext)), + LoggerFactory = CreateLoggerFactory(loggingDatabaseOptions), }); // We don't want anyone running the old migration tool accidentally @@ -1957,9 +1955,9 @@ public static async Task Migrate(DatabaseOptions fromDatabaseOptions, DatabaseType = fromDatabaseOptions.Type, ExplicitLoad = false, LazyLoading = false, - LoggerFactory = default, + LoggerFactory = CreateLoggerFactory(fromDatabaseOptions), QueryTrackingBehavior = default, - ReadOnly = false + ReadOnly = false, }; DatabaseOptions toDatabaseOptions; @@ -2017,7 +2015,8 @@ public static async Task Migrate(DatabaseOptions fromDatabaseOptions, Port = port, Database = database, Username = username, - Password = password + Password = password, + LogLevel = fromDatabaseOptions.LogLevel, }; toContextOptions = new() { @@ -2025,7 +2024,8 @@ public static async Task Migrate(DatabaseOptions fromDatabaseOptions, toDatabaseOptions, default ), - DatabaseType = toDatabaseType + DatabaseType = toDatabaseType, + LoggerFactory = CreateLoggerFactory(toDatabaseOptions), }; try @@ -2099,14 +2099,19 @@ public static async Task Migrate(DatabaseOptions fromDatabaseOptions, File.Delete(dbFileName); } - toDatabaseOptions = new() { Type = toDatabaseType }; + toDatabaseOptions = new() + { + LogLevel = fromDatabaseOptions.LogLevel, + Type = toDatabaseType, + }; toContextOptions = new() { ConnectionStringBuilder = toDatabaseType.CreateConnectionStringBuilder( toDatabaseOptions, dbFileName ), - DatabaseType = toDatabaseType + DatabaseType = toDatabaseType, + LoggerFactory = CreateLoggerFactory(toDatabaseOptions), }; break; diff --git a/Intersect.Server.Core/Database/IntersectDbContext.cs b/Intersect.Server.Core/Database/IntersectDbContext.cs index ac3884d1a1..8979372c4d 100644 --- a/Intersect.Server.Core/Database/IntersectDbContext.cs +++ b/Intersect.Server.Core/Database/IntersectDbContext.cs @@ -6,9 +6,6 @@ using Intersect.Core; using Intersect.Framework.Reflection; using Intersect.Server.Core; -#if DIAGNOSTIC -using Intersect.Server.Database.PlayerData; -#endif using Intersect.Server.Database.PlayerData.Players; using Intersect.Server.Entities; using Microsoft.EntityFrameworkCore; @@ -91,21 +88,15 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) #endif var loggerFactory = ContextOptions.LoggerFactory; -#if DIAGNOSTIC - if (this is PlayerContext) - { - loggerFactory ??= new IntersectLoggerFactory(GetType().GetName(qualified: true)); - } -#endif var enableSensitiveDataLogging = ContextOptions.EnableSensitiveDataLogging; -#if DIAGNOSTIC - enableSensitiveDataLogging = this is PlayerContext; +#if DEBUG + enableSensitiveDataLogging = Debugger.IsAttached; #endif var enableDetailedErrors = ContextOptions.EnableDetailedErrors; -#if DIAGNOSTIC - enableDetailedErrors = this is PlayerContext; +#if DEBUG + enableDetailedErrors = Debugger.IsAttached; #endif _ = optionsBuilder diff --git a/Intersect.Server.Core/Database/IntersectLoggerFactory.cs b/Intersect.Server.Core/Database/IntersectLoggerFactory.cs deleted file mode 100644 index d78ef7e800..0000000000 --- a/Intersect.Server.Core/Database/IntersectLoggerFactory.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System.Diagnostics; -using Intersect.Core; -using Intersect.Framework.Reflection; -using Microsoft.Extensions.Logging; -using Serilog; -using Serilog.Core; -using Serilog.Events; -using Serilog.Extensions.Logging; -using ILogger = Microsoft.Extensions.Logging.ILogger; - -namespace Intersect.Server.Database; - -internal sealed class IntersectLoggerFactory : ILoggerFactory -{ - private static readonly Dictionary LoggersByName = new(); - - private readonly ILoggerFactory _loggerFactory; - - internal IntersectLoggerFactory(string name) - { - if (!LoggersByName.TryGetValue(name, out var logger)) - { - var configuration = new LoggerConfiguration().Enrich.FromLogContext().WriteTo - .Console(restrictedToMinimumLevel: Debugger.IsAttached ? LogEventLevel.Warning : LogEventLevel.Error) - .WriteTo.File(path: $"logs/db-{name}.log").WriteTo.File( - path: $"logs/db-errors-{name}.log", - restrictedToMinimumLevel: LogEventLevel.Error, - rollOnFileSizeLimit: true, - retainedFileTimeLimit: TimeSpan.FromDays(30) - ); - LoggersByName[name] = configuration.CreateLogger(); - } - - _loggerFactory = new SerilogLoggerFactory(logger); - } - - public void AddProvider(ILoggerProvider provider) - { - ApplicationContext.Context.Value?.Logger.LogWarning($"Tried to add provider but this is not implemented: {provider.GetFullishName()}"); - } - - public ILogger CreateLogger() => _loggerFactory.CreateLogger(); - - public ILogger CreateLogger(string categoryName) => _loggerFactory.CreateLogger(categoryName); - - public void Dispose() - { - } -} \ No newline at end of file diff --git a/Intersect.Server.Core/Database/PlayerData/Players/Guild.cs b/Intersect.Server.Core/Database/PlayerData/Players/Guild.cs index 9d45136231..ea12a38a9e 100644 --- a/Intersect.Server.Core/Database/PlayerData/Players/Guild.cs +++ b/Intersect.Server.Core/Database/PlayerData/Players/Guild.cs @@ -117,13 +117,18 @@ public Guild() return null; } + using var context = DbInterface.CreatePlayerContext(readOnly: false); + + creator.Save(context); + var guild = new Guild { Name = name, FoundingDate = DateTime.UtcNow, GuildInstanceId = Guid.NewGuid(), }; + context.Guilds.Add(guild); SlotHelper.ValidateSlotList(guild.Bank, Options.Instance.Guild.InitialBankSlots);