From 55160ff4340cd93c1d88e40f70ef0d3f50acb342 Mon Sep 17 00:00:00 2001 From: jvyden Date: Sun, 1 May 2022 18:34:26 -0400 Subject: [PATCH] Make internal logging use an enum instead of a string for areas --- .../Controllers/GameApi/LoginController.cs | 14 +++++----- .../GameApi/Matching/MatchController.cs | 10 +++---- .../Controllers/GameApi/MessageController.cs | 2 +- .../GameApi/Resources/PhotosController.cs | 4 +-- .../GameApi/Resources/ResourcesController.cs | 9 ++++--- .../GameApi/Slots/CollectionController.cs | 2 +- .../Controllers/Website/SlotPageController.cs | 4 +-- .../Controllers/Website/UserPageController.cs | 4 +-- ProjectLighthouse/Helpers/FileHelper.cs | 2 +- ProjectLighthouse/Helpers/InfluxHelper.cs | 10 +++---- ProjectLighthouse/Helpers/RoomHelper.cs | 8 +++--- ProjectLighthouse/Helpers/VersionHelper.cs | 4 +-- ProjectLighthouse/Logging/LogArea.cs | 21 +++++++++++++++ ProjectLighthouse/Logging/Logger.cs | 22 ++++++++-------- .../Maintenance/Commands/CreateUserCommand.cs | 8 +++--- ProjectLighthouse/Pages/LoginForm.cshtml.cs | 10 +++---- .../Pages/SetEmailForm.cshtml.cs | 2 +- ProjectLighthouse/Program.cs | 26 +++++++++---------- .../Startup/DebugWarmupLifetime.cs | 8 +++--- ProjectLighthouse/Startup/Startup.cs | 6 ++--- .../Types/Categories/CategoryWithUser.cs | 8 +++--- .../Types/Settings/ServerSettings.cs | 12 ++++----- .../Types/Settings/ServerStatics.cs | 2 +- ProjectLighthouse/Types/Tickets/NPTicket.cs | 25 +++++++++--------- 24 files changed, 123 insertions(+), 100 deletions(-) create mode 100644 ProjectLighthouse/Logging/LogArea.cs diff --git a/ProjectLighthouse/Controllers/GameApi/LoginController.cs b/ProjectLighthouse/Controllers/GameApi/LoginController.cs index e5575ee2..364215ff 100644 --- a/ProjectLighthouse/Controllers/GameApi/LoginController.cs +++ b/ProjectLighthouse/Controllers/GameApi/LoginController.cs @@ -45,14 +45,14 @@ public class LoginController : ControllerBase if (npTicket == null) { - Logger.LogWarn("npTicket was null, rejecting login", "Login"); + Logger.LogWarn("npTicket was null, rejecting login", LogArea.Login); return this.BadRequest(); } IPAddress? remoteIpAddress = this.HttpContext.Connection.RemoteIpAddress; if (remoteIpAddress == null) { - Logger.LogWarn("unable to determine ip, rejecting login", "Login"); + Logger.LogWarn("unable to determine ip, rejecting login", LogArea.Login); return this.StatusCode(403, ""); // 403 probably isnt the best status code for this, but whatever } @@ -68,7 +68,7 @@ public class LoginController : ControllerBase token = await this.database.AuthenticateUser(npTicket, ipAddress); if (token == null) { - Logger.LogWarn($"Unable to find/generate a token for username {npTicket.Username}", "Login"); + Logger.LogWarn($"Unable to find/generate a token for username {npTicket.Username}", LogArea.Login); return this.StatusCode(403, ""); // If not, then 403. } } @@ -77,7 +77,7 @@ public class LoginController : ControllerBase if (user == null || user.Banned) { - Logger.LogError($"Unable to find user {npTicket.Username} from token", "Login"); + Logger.LogError($"Unable to find user {npTicket.Username} from token", LogArea.Login); return this.StatusCode(403, ""); } @@ -94,7 +94,7 @@ public class LoginController : ControllerBase DeniedAuthenticationHelper.AddAttempt(ipAddressAndName); await this.database.SaveChangesAsync(); - Logger.LogWarn($"Too many recent denied logins from user {user.Username}, rejecting login", "Login"); + Logger.LogWarn($"Too many recent denied logins from user {user.Username}, rejecting login", LogArea.Login); return this.StatusCode(403, ""); } } @@ -126,11 +126,11 @@ public class LoginController : ControllerBase if (!token.Approved) { - Logger.LogWarn($"Token unapproved for user {user.Username}, rejecting login", "Login"); + Logger.LogWarn($"Token unapproved for user {user.Username}, rejecting login", LogArea.Login); return this.StatusCode(403, ""); } - Logger.LogSuccess($"Successfully logged in user {user.Username} as {token.GameVersion} client", "Login"); + Logger.LogSuccess($"Successfully logged in user {user.Username} as {token.GameVersion} client", LogArea.Login); // After this point we are now considering this session as logged in. // We just logged in with the token. Mark it as used so someone else doesnt try to use it, diff --git a/ProjectLighthouse/Controllers/GameApi/Matching/MatchController.cs b/ProjectLighthouse/Controllers/GameApi/Matching/MatchController.cs index 3d6c13be..e066097c 100644 --- a/ProjectLighthouse/Controllers/GameApi/Matching/MatchController.cs +++ b/ProjectLighthouse/Controllers/GameApi/Matching/MatchController.cs @@ -47,7 +47,7 @@ public class MatchController : ControllerBase if (bodyString.Length == 0 || bodyString[0] != '[') return this.BadRequest(); - Logger.LogInfo("Received match data: " + bodyString, "Match"); + Logger.LogInfo("Received match data: " + bodyString, LogArea.Match); IMatchData? matchData; try @@ -56,19 +56,19 @@ public class MatchController : ControllerBase } catch(Exception e) { - Logger.LogError("Exception while parsing matchData: ", "Match"); - Logger.LogError(e.ToDetailedException(), "Match"); + Logger.LogError("Exception while parsing matchData: ", LogArea.Match); + Logger.LogError(e.ToDetailedException(), LogArea.Match); return this.BadRequest(); } if (matchData == null) { - Logger.LogError($"Could not parse match data: {nameof(matchData)} is null", "Match"); + Logger.LogError($"Could not parse match data: {nameof(matchData)} is null", LogArea.Match); return this.BadRequest(); } - Logger.LogError($"Parsed match from {user.Username} (type: {matchData.GetType()})", "Match"); + Logger.LogError($"Parsed match from {user.Username} (type: {matchData.GetType()})", LogArea.Match); #endregion diff --git a/ProjectLighthouse/Controllers/GameApi/MessageController.cs b/ProjectLighthouse/Controllers/GameApi/MessageController.cs index cef39b87..667fbcd8 100644 --- a/ProjectLighthouse/Controllers/GameApi/MessageController.cs +++ b/ProjectLighthouse/Controllers/GameApi/MessageController.cs @@ -98,7 +98,7 @@ along with this program. If not, see ."; string scannedText = CensorHelper.ScanMessage(response); - Logger.LogInfo($"{user.Username}: {response} / {scannedText}", "Filter"); + Logger.LogInfo($"{user.Username}: {response} / {scannedText}", LogArea.Filter); return this.Ok(scannedText); } diff --git a/ProjectLighthouse/Controllers/GameApi/Resources/PhotosController.cs b/ProjectLighthouse/Controllers/GameApi/Resources/PhotosController.cs index 7ffe5116..bf646cda 100644 --- a/ProjectLighthouse/Controllers/GameApi/Resources/PhotosController.cs +++ b/ProjectLighthouse/Controllers/GameApi/Resources/PhotosController.cs @@ -67,7 +67,7 @@ public class PhotosController : ControllerBase if (subject.User == null) continue; subject.UserId = subject.User.UserId; - Logger.LogDebug($"Adding PhotoSubject (userid {subject.UserId}) to db", "Photos"); + Logger.LogDebug($"Adding PhotoSubject (userid {subject.UserId}) to db", LogArea.Photos); this.database.PhotoSubjects.Add(subject); } @@ -87,7 +87,7 @@ public class PhotosController : ControllerBase // photo.Slot = await this.database.Slots.FirstOrDefaultAsync(s => s.SlotId == photo.SlotId); - Logger.LogDebug($"Adding PhotoSubjectCollection ({photo.PhotoSubjectCollection}) to photo", "Photos"); + Logger.LogDebug($"Adding PhotoSubjectCollection ({photo.PhotoSubjectCollection}) to photo", LogArea.Photos); this.database.Photos.Add(photo); diff --git a/ProjectLighthouse/Controllers/GameApi/Resources/ResourcesController.cs b/ProjectLighthouse/Controllers/GameApi/Resources/ResourcesController.cs index 1ba1ee2e..1afd41f7 100644 --- a/ProjectLighthouse/Controllers/GameApi/Resources/ResourcesController.cs +++ b/ProjectLighthouse/Controllers/GameApi/Resources/ResourcesController.cs @@ -96,23 +96,24 @@ public class ResourcesController : ControllerBase // lbp treats code 409 as success and as an indicator that the file is already present if (FileHelper.ResourceExists(hash)) this.Conflict(); - Logger.LogInfo($"Processing resource upload (hash: {hash})", "Resources"); + Logger.LogInfo($"Processing resource upload (hash: {hash})", LogArea.Resources); LbpFile file = new(await BinaryHelper.ReadFromPipeReader(this.Request.BodyReader)); if (!FileHelper.IsFileSafe(file)) { - Logger.LogWarn($"File is unsafe (hash: {hash}, type: {file.FileType})", "Resources"); + Logger.LogWarn($"File is unsafe (hash: {hash}, type: {file.FileType})", LogArea.Resources); return this.Conflict(); } string calculatedHash = file.Hash; if (calculatedHash != hash) { - Logger.LogWarn($"File hash does not match the uploaded file! (hash: {hash}, calculatedHash: {calculatedHash}, type: {file.FileType})", "Resources"); + Logger.LogWarn + ($"File hash does not match the uploaded file! (hash: {hash}, calculatedHash: {calculatedHash}, type: {file.FileType})", LogArea.Resources); return this.Conflict(); } - Logger.LogSuccess($"File is OK! (hash: {hash}, type: {file.FileType})", "Resources"); + Logger.LogSuccess($"File is OK! (hash: {hash}, type: {file.FileType})", LogArea.Resources); await IOFile.WriteAllBytesAsync(path, file.Data); return this.Ok(); } diff --git a/ProjectLighthouse/Controllers/GameApi/Slots/CollectionController.cs b/ProjectLighthouse/Controllers/GameApi/Slots/CollectionController.cs index 3386aabb..7531a69d 100644 --- a/ProjectLighthouse/Controllers/GameApi/Slots/CollectionController.cs +++ b/ProjectLighthouse/Controllers/GameApi/Slots/CollectionController.cs @@ -84,7 +84,7 @@ public class CollectionController : ControllerBase Category? category = CollectionHelper.Categories.FirstOrDefault(c => c.Endpoint == endpointName); if (category == null) return this.NotFound(); - Logger.LogDebug("Found category " + category, "Category"); + Logger.LogDebug("Found category " + category, LogArea.Category); List slots; int totalSlots; diff --git a/ProjectLighthouse/Controllers/Website/SlotPageController.cs b/ProjectLighthouse/Controllers/Website/SlotPageController.cs index 1df0e966..d3fddc25 100644 --- a/ProjectLighthouse/Controllers/Website/SlotPageController.cs +++ b/ProjectLighthouse/Controllers/Website/SlotPageController.cs @@ -44,14 +44,14 @@ public class SlotPageController : ControllerBase if (msg == null) { - Logger.LogError($"Refusing to post comment from {user.UserId} on user {id}, {nameof(msg)} is null", "Comments"); + Logger.LogError($"Refusing to post comment from {user.UserId} on user {id}, {nameof(msg)} is null", LogArea.Comments); return this.Redirect("~/slot/" + id); } msg = SanitizationHelper.SanitizeString(msg); await this.database.PostComment(user, id, CommentType.Level, msg); - Logger.LogSuccess($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", "Comments"); + Logger.LogSuccess($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", LogArea.Comments); return this.Redirect("~/slot/" + id); } diff --git a/ProjectLighthouse/Controllers/Website/UserPageController.cs b/ProjectLighthouse/Controllers/Website/UserPageController.cs index fbb35518..107f1eed 100644 --- a/ProjectLighthouse/Controllers/Website/UserPageController.cs +++ b/ProjectLighthouse/Controllers/Website/UserPageController.cs @@ -38,14 +38,14 @@ public class UserPageController : ControllerBase if (msg == null) { - Logger.LogError($"Refusing to post comment from {user.UserId} on user {id}, {nameof(msg)} is null", "Comments"); + Logger.LogError($"Refusing to post comment from {user.UserId} on user {id}, {nameof(msg)} is null", LogArea.Comments); return this.Redirect("~/user/" + id); } msg = SanitizationHelper.SanitizeString(msg); await this.database.PostComment(user, id, CommentType.Profile, msg); - Logger.LogSuccess($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", "Comments"); + Logger.LogSuccess($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", LogArea.Comments); return this.Redirect("~/user/" + id); } diff --git a/ProjectLighthouse/Helpers/FileHelper.cs b/ProjectLighthouse/Helpers/FileHelper.cs index 3d9b1f74..a4e18379 100644 --- a/ProjectLighthouse/Helpers/FileHelper.cs +++ b/ProjectLighthouse/Helpers/FileHelper.cs @@ -114,7 +114,7 @@ public static class FileHelper EnsureDirectoryCreated(Path.Combine(Environment.CurrentDirectory, "png")); if (Directory.Exists("r")) { - Logger.LogInfo("Converting all textures to PNG. This may take a while if this is the first time running this operation...", "Startup"); + Logger.LogInfo("Converting all textures to PNG. This may take a while if this is the first time running this operation...", LogArea.Startup); ConcurrentQueue fileQueue = new(); diff --git a/ProjectLighthouse/Helpers/InfluxHelper.cs b/ProjectLighthouse/Helpers/InfluxHelper.cs index 07980b9c..5a607446 100644 --- a/ProjectLighthouse/Helpers/InfluxHelper.cs +++ b/ProjectLighthouse/Helpers/InfluxHelper.cs @@ -49,8 +49,8 @@ public static class InfluxHelper } catch(Exception e) { - Logger.LogError("Exception while logging: ", "InfluxDB"); - Logger.LogError(e.ToDetailedException(), "InfluxDB"); + Logger.LogError("Exception while logging: ", LogArea.InfluxDB); + Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); } } @@ -58,7 +58,7 @@ public static class InfluxHelper public static async Task StartLogging() { await Client.ReadyAsync(); - Logger.LogSuccess("InfluxDB is now ready.", "InfluxDB"); + Logger.LogSuccess("InfluxDB is now ready.", LogArea.InfluxDB); Thread t = new ( delegate() @@ -71,8 +71,8 @@ public static class InfluxHelper } catch(Exception e) { - Logger.LogError("Exception while running log thread: ", "InfluxDB"); - Logger.LogError(e.ToDetailedException(), "InfluxDB"); + Logger.LogError("Exception while running log thread: ", LogArea.InfluxDB); + Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); } Thread.Sleep(60000); diff --git a/ProjectLighthouse/Helpers/RoomHelper.cs b/ProjectLighthouse/Helpers/RoomHelper.cs index c54ee939..b925f55b 100644 --- a/ProjectLighthouse/Helpers/RoomHelper.cs +++ b/ProjectLighthouse/Helpers/RoomHelper.cs @@ -45,7 +45,7 @@ public class RoomHelper { if (roomVersion == GameVersion.LittleBigPlanet1 || roomVersion == GameVersion.LittleBigPlanetPSP) { - Logger.LogError($"Returning null for FindBestRoom, game ({roomVersion}) does not support dive in (should never happen?)", "Match"); + Logger.LogError($"Returning null for FindBestRoom, game ({roomVersion}) does not support dive in (should never happen?)", LogArea.Match); return null; } @@ -139,7 +139,7 @@ public class RoomHelper }, }; - Logger.LogSuccess($"Found a room (id: {room.RoomId}) for user {user?.Username ?? "null"} (id: {user?.UserId ?? -1})", "Match"); + Logger.LogSuccess($"Found a room (id: {room.RoomId}) for user {user?.Username ?? "null"} (id: {user?.UserId ?? -1})", LogArea.Match); return response; } @@ -172,7 +172,7 @@ public class RoomHelper CleanupRooms(room.Host, room); lock(Rooms) Rooms.Add(room); - Logger.LogInfo($"Created room (id: {room.RoomId}) for host {room.Host.Username} (id: {room.Host.UserId})", "Match"); + Logger.LogInfo($"Created room (id: {room.RoomId}) for host {room.Host.Username} (id: {room.Host.UserId})", LogArea.Match); return room; } @@ -237,7 +237,7 @@ public class RoomHelper if (roomCountBeforeCleanup != roomCountAfterCleanup) { - Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", "Match"); + Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", LogArea.Match); } } } diff --git a/ProjectLighthouse/Helpers/VersionHelper.cs b/ProjectLighthouse/Helpers/VersionHelper.cs index 6e91087e..40c95a84 100644 --- a/ProjectLighthouse/Helpers/VersionHelper.cs +++ b/ProjectLighthouse/Helpers/VersionHelper.cs @@ -33,7 +33,7 @@ public static class VersionHelper ( "Project Lighthouse was built incorrectly. Please make sure git is available when building. " + "Because of this, you will not be notified of updates.", - "Startup" + LogArea.Startup ); CommitHash = "invalid"; Branch = "invalid"; @@ -46,7 +46,7 @@ public static class VersionHelper ( "This is a modified version of Project Lighthouse. " + "Please make sure you are properly disclosing the source code to any users who may be using this instance.", - "Startup" + LogArea.Startup ); CanCheckForUpdates = false; } diff --git a/ProjectLighthouse/Logging/LogArea.cs b/ProjectLighthouse/Logging/LogArea.cs new file mode 100644 index 00000000..a43c59b8 --- /dev/null +++ b/ProjectLighthouse/Logging/LogArea.cs @@ -0,0 +1,21 @@ +using System.Diagnostics.CodeAnalysis; + +namespace LBPUnion.ProjectLighthouse.Logging; + +[SuppressMessage("ReSharper", "InconsistentNaming")] +public enum LogArea +{ + Login, + Startup, + Category, + Comments, + Config, + Database, + Filter, + HTTP, + InfluxDB, + Match, + Photos, + Resources, + Logger, +} \ No newline at end of file diff --git a/ProjectLighthouse/Logging/Logger.cs b/ProjectLighthouse/Logging/Logger.cs index 45283ddb..9c9f3af1 100644 --- a/ProjectLighthouse/Logging/Logger.cs +++ b/ProjectLighthouse/Logging/Logger.cs @@ -28,7 +28,7 @@ public static class Logger public static void AddLogger(ILogger logger) { loggers.Add(logger); - LogSuccess("Initialized " + logger.GetType().Name, "Logger"); + LogSuccess("Initialized " + logger.GetType().Name, LogArea.Logger); } private static LogTrace getTrace(int extraTraceLines = 0) @@ -144,31 +144,31 @@ public static class Logger #region Logging functions - public static void LogDebug(string text, string area = "") + public static void LogDebug(string text, LogArea logArea) { #if DEBUG - Log(text, area, LogLevel.Debug); + Log(text, logArea.ToString(), LogLevel.Debug); #endif } - public static void LogSuccess(string text, string area = "") + public static void LogSuccess(string text, LogArea logArea) { - Log(text, area, LogLevel.Success); + Log(text, logArea.ToString(), LogLevel.Success); } - public static void LogInfo(string text, string area = "") + public static void LogInfo(string text, LogArea logArea) { - Log(text, area, LogLevel.Info); + Log(text, logArea.ToString(), LogLevel.Info); } - public static void LogWarn(string text, string area = "") + public static void LogWarn(string text, LogArea logArea) { - Log(text, area, LogLevel.Warning); + Log(text, logArea.ToString(), LogLevel.Warning); } - public static void LogError(string text, string area = "") + public static void LogError(string text, LogArea logArea) { - Log(text, area, LogLevel.Error); + Log(text, logArea.ToString(), LogLevel.Error); } public static void Log(string text, string area, LogLevel level, int extraTraceLines = 0) diff --git a/ProjectLighthouse/Maintenance/Commands/CreateUserCommand.cs b/ProjectLighthouse/Maintenance/Commands/CreateUserCommand.cs index 11bbd8b7..775a6cd3 100644 --- a/ProjectLighthouse/Maintenance/Commands/CreateUserCommand.cs +++ b/ProjectLighthouse/Maintenance/Commands/CreateUserCommand.cs @@ -24,17 +24,17 @@ public class CreateUserCommand : ICommand if (user == null) { user = await this._database.CreateUser(onlineId, CryptoHelper.BCryptHash(password)); - Logger.LogSuccess($"Created user {user.UserId} with online ID (username) {user.Username} and the specified password.", "Login"); + Logger.LogSuccess($"Created user {user.UserId} with online ID (username) {user.Username} and the specified password.", LogArea.Login); user.PasswordResetRequired = true; - Logger.LogInfo("This user will need to reset their password when they log in.", "Login"); + Logger.LogInfo("This user will need to reset their password when they log in.", LogArea.Login); await this._database.SaveChangesAsync(); - Logger.LogInfo("Database changes saved.", "Database"); + Logger.LogInfo("Database changes saved.", LogArea.Database); } else { - Logger.LogError("A user with this username already exists.", "Login"); + Logger.LogError("A user with this username already exists.", LogArea.Login); } } diff --git a/ProjectLighthouse/Pages/LoginForm.cshtml.cs b/ProjectLighthouse/Pages/LoginForm.cshtml.cs index ac424b17..3cdd72cf 100644 --- a/ProjectLighthouse/Pages/LoginForm.cshtml.cs +++ b/ProjectLighthouse/Pages/LoginForm.cshtml.cs @@ -46,28 +46,28 @@ public class LoginForm : BaseLayout User? user = await this.Database.Users.FirstOrDefaultAsync(u => u.Username == username); if (user == null) { - Logger.LogWarn($"User {username} failed to login on web due to invalid username", "Login"); + Logger.LogWarn($"User {username} failed to login on web due to invalid username", LogArea.Login); this.Error = "The username or password you entered is invalid."; return this.Page(); } if (!BCrypt.Net.BCrypt.Verify(password, user.Password)) { - Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login on web due to invalid password", "Login"); + Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login on web due to invalid password", LogArea.Login); this.Error = "The username or password you entered is invalid."; return this.Page(); } if (user.Banned) { - Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login on web due to being banned", "Login"); + Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login on web due to being banned", LogArea.Login); this.Error = "You have been banned. Please contact an administrator for more information.\nReason: " + user.BannedReason; return this.Page(); } if (user.EmailAddress == null && ServerSettings.Instance.SMTPEnabled) { - Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login; email not set", "Login"); + Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login; email not set", LogArea.Login); EmailSetToken emailSetToken = new() { @@ -101,7 +101,7 @@ public class LoginForm : BaseLayout } ); - Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web", "Login"); + Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web", LogArea.Login); if (user.PasswordResetRequired) return this.Redirect("~/passwordResetRequired"); if (ServerSettings.Instance.SMTPEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail"); diff --git a/ProjectLighthouse/Pages/SetEmailForm.cshtml.cs b/ProjectLighthouse/Pages/SetEmailForm.cshtml.cs index 9682157f..f46c2270 100644 --- a/ProjectLighthouse/Pages/SetEmailForm.cshtml.cs +++ b/ProjectLighthouse/Pages/SetEmailForm.cshtml.cs @@ -71,7 +71,7 @@ public class SetEmailForm : BaseLayout } ); - Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web after setting an email address", "Login"); + Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web after setting an email address", LogArea.Login); this.Database.WebTokens.Add(webToken); await this.Database.SaveChangesAsync(); diff --git a/ProjectLighthouse/Program.cs b/ProjectLighthouse/Program.cs index e896107f..0889f0d3 100644 --- a/ProjectLighthouse/Program.cs +++ b/ProjectLighthouse/Program.cs @@ -27,32 +27,32 @@ public static class Program Logger.AddLogger(new ConsoleLogger()); Logger.AddLogger(new LighthouseFileLogger()); - Logger.LogInfo("Welcome to Project Lighthouse!", "Startup"); - Logger.LogInfo($"You are running version {VersionHelper.FullVersion}", "Startup"); + Logger.LogInfo("Welcome to Project Lighthouse!", LogArea.Startup); + Logger.LogInfo($"You are running version {VersionHelper.FullVersion}", LogArea.Startup); // Referencing ServerSettings.Instance here loads the config, see ServerSettings.cs for more information - Logger.LogSuccess("Loaded config file version " + ServerSettings.Instance.ConfigVersion, "Startup"); + Logger.LogSuccess("Loaded config file version " + ServerSettings.Instance.ConfigVersion, LogArea.Startup); - Logger.LogInfo("Determining if the database is available...", "Startup"); + Logger.LogInfo("Determining if the database is available...", LogArea.Startup); bool dbConnected = ServerStatics.DbConnected; if (!dbConnected) { - Logger.LogError("Database unavailable! Exiting.", "Startup"); + Logger.LogError("Database unavailable! Exiting.", LogArea.Startup); } else { - Logger.LogSuccess("Connected to the database.", "Startup"); + Logger.LogSuccess("Connected to the database.", LogArea.Startup); } if (!dbConnected) Environment.Exit(1); using Database database = new(); - Logger.LogInfo("Migrating database...", "Database"); + Logger.LogInfo("Migrating database...", LogArea.Database); MigrateDatabase(database); if (ServerSettings.Instance.InfluxEnabled) { - Logger.LogInfo("Influx logging is enabled. Starting influx logging...", "Startup"); + Logger.LogInfo("Influx logging is enabled. Starting influx logging...", LogArea.Startup); InfluxHelper.StartLogging().Wait(); if (ServerSettings.Instance.InfluxLoggingEnabled) Logger.AddLogger(new InfluxLogger()); } @@ -62,9 +62,9 @@ public static class Program "This is a debug build, so performance may suffer! " + "If you are running Lighthouse in a production environment, " + "it is highly recommended to run a release build. ", - "Startup" + LogArea.Startup ); - Logger.LogDebug("You can do so by running any dotnet command with the flag: \"-c Release\". ", "Startup"); + Logger.LogDebug("You can do so by running any dotnet command with the flag: \"-c Release\". ", LogArea.Startup); if (args.Length != 0) { @@ -74,11 +74,11 @@ public static class Program if (ServerSettings.Instance.ConvertAssetsOnStartup) FileHelper.ConvertAllTexturesToPng(); - Logger.LogInfo("Starting room cleanup thread...", "Startup"); + Logger.LogInfo("Starting room cleanup thread...", LogArea.Startup); RoomHelper.StartCleanupThread(); stopwatch.Stop(); - Logger.LogSuccess($"Ready! Startup took {stopwatch.ElapsedMilliseconds}ms. Passing off control to ASP.NET...", "Startup"); + Logger.LogSuccess($"Ready! Startup took {stopwatch.ElapsedMilliseconds}ms. Passing off control to ASP.NET...", LogArea.Startup); CreateHostBuilder(args).Build().Run(); } @@ -91,7 +91,7 @@ public static class Program database.Database.MigrateAsync().Wait(); stopwatch.Stop(); - Logger.LogSuccess($"Migration took {stopwatch.ElapsedMilliseconds}ms.", "Database"); + Logger.LogSuccess($"Migration took {stopwatch.ElapsedMilliseconds}ms.", LogArea.Database); } public static IHostBuilder CreateHostBuilder(string[] args) diff --git a/ProjectLighthouse/Startup/DebugWarmupLifetime.cs b/ProjectLighthouse/Startup/DebugWarmupLifetime.cs index 74372120..f4d3ad2f 100644 --- a/ProjectLighthouse/Startup/DebugWarmupLifetime.cs +++ b/ProjectLighthouse/Startup/DebugWarmupLifetime.cs @@ -40,18 +40,18 @@ public class DebugWarmupLifetime : IHostLifetime string url = ServerSettings.Instance.ServerListenUrl; url = url.Replace("0.0.0.0", "127.0.0.1"); - Logger.LogDebug("Warming up Hot Reload...", "Startup"); + Logger.LogDebug("Warming up Hot Reload...", LogArea.Startup); try { client.GetAsync(url).Wait(); } catch(Exception e) { - Logger.LogDebug("An error occurred while attempting to warm up hot reload. Initial page load will be delayed.", "Startup"); - Logger.LogDebug(e.ToDetailedException(), "Startup"); + Logger.LogDebug("An error occurred while attempting to warm up hot reload. Initial page load will be delayed.", LogArea.Startup); + Logger.LogDebug(e.ToDetailedException(), LogArea.Startup); return; } - Logger.LogSuccess("Hot Reload is ready to go!", "Startup"); + Logger.LogSuccess("Hot Reload is ready to go!", LogArea.Startup); } public Task StopAsync(CancellationToken cancellationToken) => this.consoleLifetime.StopAsync(cancellationToken); diff --git a/ProjectLighthouse/Startup/Startup.cs b/ProjectLighthouse/Startup/Startup.cs index e86e509b..a2a149f8 100644 --- a/ProjectLighthouse/Startup/Startup.cs +++ b/ProjectLighthouse/Startup/Startup.cs @@ -102,7 +102,7 @@ public class Startup ( "The serverDigestKey configuration option wasn't set, so digest headers won't be set or verified. This will also prevent LBP 1, LBP 2, and LBP Vita from working. " + "To increase security, it is recommended that you find and set this variable.", - "Startup" + LogArea.Startup ); computeDigests = false; } @@ -144,7 +144,7 @@ public class Startup Logger.LogInfo ( $"{context.Response.StatusCode}, {requestStopwatch.ElapsedMilliseconds}ms: {context.Request.Method} {context.Request.Path}{context.Request.QueryString}", - "HTTP" + LogArea.HTTP ); #if DEBUG @@ -152,7 +152,7 @@ public class Startup if (context.Request.Method == "POST") { context.Request.Body.Position = 0; - Logger.LogDebug(await new StreamReader(context.Request.Body).ReadToEndAsync(), "HTTP"); + Logger.LogDebug(await new StreamReader(context.Request.Body).ReadToEndAsync(), LogArea.HTTP); } #endif } diff --git a/ProjectLighthouse/Types/Categories/CategoryWithUser.cs b/ProjectLighthouse/Types/Categories/CategoryWithUser.cs index 630d4b56..53d18388 100644 --- a/ProjectLighthouse/Types/Categories/CategoryWithUser.cs +++ b/ProjectLighthouse/Types/Categories/CategoryWithUser.cs @@ -13,7 +13,7 @@ public abstract class CategoryWithUser : Category public override Slot? GetPreviewSlot(Database database) { #if DEBUG - Logger.LogError("tried to get preview slot without user on CategoryWithUser", "Category"); + Logger.LogError("tried to get preview slot without user on CategoryWithUser", LogArea.Category); if (Debugger.IsAttached) Debugger.Break(); #endif return null; @@ -23,7 +23,7 @@ public abstract class CategoryWithUser : Category public override int GetTotalSlots(Database database) { #if DEBUG - Logger.LogError("tried to get total slots without user on CategoryWithUser", "Category"); + Logger.LogError("tried to get total slots without user on CategoryWithUser", LogArea.Category); if (Debugger.IsAttached) Debugger.Break(); #endif return -1; @@ -33,7 +33,7 @@ public abstract class CategoryWithUser : Category public override IEnumerable GetSlots(Database database, int pageStart, int pageSize) { #if DEBUG - Logger.LogError("tried to get slots without user on CategoryWithUser", "Category"); + Logger.LogError("tried to get slots without user on CategoryWithUser", LogArea.Category); if (Debugger.IsAttached) Debugger.Break(); #endif return new List(); @@ -41,7 +41,7 @@ public abstract class CategoryWithUser : Category public new string Serialize(Database database) { - Logger.LogError("tried to serialize without user on CategoryWithUser", "Category"); + Logger.LogError("tried to serialize without user on CategoryWithUser", LogArea.Category); return string.Empty; } diff --git a/ProjectLighthouse/Types/Settings/ServerSettings.cs b/ProjectLighthouse/Types/Settings/ServerSettings.cs index 7f0b5c6a..b5c9c34a 100644 --- a/ProjectLighthouse/Types/Settings/ServerSettings.cs +++ b/ProjectLighthouse/Types/Settings/ServerSettings.cs @@ -19,7 +19,7 @@ public class ServerSettings { if (ServerStatics.IsUnitTesting) return; // Unit testing, we don't want to read configurations here since the tests will provide their own - Logger.LogInfo("Loading config...", "Config"); + Logger.LogInfo("Loading config...", LogArea.Config); if (File.Exists(ConfigFileName)) { @@ -29,7 +29,7 @@ public class ServerSettings if (Instance.ConfigVersion < CurrentConfigVersion) { - Logger.LogInfo($"Upgrading config file from version {Instance.ConfigVersion} to version {CurrentConfigVersion}", "Config"); + Logger.LogInfo($"Upgrading config file from version {Instance.ConfigVersion} to version {CurrentConfigVersion}", LogArea.Config); Instance.ConfigVersion = CurrentConfigVersion; configFile = JsonSerializer.Serialize ( @@ -63,7 +63,7 @@ public class ServerSettings "The configuration file was not found. " + "A blank configuration file has been created for you at " + $"{Path.Combine(Environment.CurrentDirectory, ConfigFileName)}", - "Config" + LogArea.Config ); Environment.Exit(1); @@ -72,7 +72,7 @@ public class ServerSettings // Set up reloading if (Instance.ConfigReloading) { - Logger.LogInfo("Setting up config reloading...", "Config"); + Logger.LogInfo("Setting up config reloading...", LogArea.Config); fileWatcher = new FileSystemWatcher { Path = Environment.CurrentDirectory, @@ -89,8 +89,8 @@ public class ServerSettings private static void onConfigChanged(object sender, FileSystemEventArgs e) { Debug.Assert(e.Name == ConfigFileName); - Logger.LogInfo("Configuration file modified, reloading config.", "Config"); - Logger.LogWarn("Some changes may not apply, in which case may require a restart of Project Lighthouse.", "Config"); + Logger.LogInfo("Configuration file modified, reloading config.", LogArea.Config); + Logger.LogWarn("Some changes may not apply, in which case may require a restart of Project Lighthouse.", LogArea.Config); string configFile = File.ReadAllText(ConfigFileName); Instance = JsonSerializer.Deserialize(configFile) ?? throw new ArgumentNullException(nameof(ConfigFileName)); diff --git a/ProjectLighthouse/Types/Settings/ServerStatics.cs b/ProjectLighthouse/Types/Settings/ServerStatics.cs index 98703d11..3753859c 100644 --- a/ProjectLighthouse/Types/Settings/ServerStatics.cs +++ b/ProjectLighthouse/Types/Settings/ServerStatics.cs @@ -19,7 +19,7 @@ public static class ServerStatics } catch(Exception e) { - Logger.LogError(e.ToString(), "Database"); + Logger.LogError(e.ToString(), LogArea.Database); return false; } } diff --git a/ProjectLighthouse/Types/Tickets/NPTicket.cs b/ProjectLighthouse/Types/Tickets/NPTicket.cs index 32d3c2e8..f199cfb7 100644 --- a/ProjectLighthouse/Types/Tickets/NPTicket.cs +++ b/ProjectLighthouse/Types/Tickets/NPTicket.cs @@ -93,7 +93,7 @@ public class NPTicket reader.ReadUInt16BE(); // Ticket length, we don't care about this SectionHeader bodyHeader = reader.ReadSectionHeader(); - Logger.LogDebug($"bodyHeader.Type is {bodyHeader.Type}", "Login"); + Logger.LogDebug($"bodyHeader.Type is {bodyHeader.Type}", LogArea.Login); switch (npTicket.ticketVersion) { @@ -115,13 +115,13 @@ public class NPTicket npTicket.titleId = npTicket.titleId.Substring(0, npTicket.titleId.Length - 3); // Trim _00 at the end // Data now (hopefully): BCUS98245 - Logger.LogDebug($"titleId is {npTicket.titleId}", "Login"); + Logger.LogDebug($"titleId is {npTicket.titleId}", LogArea.Login); npTicket.GameVersion = GameVersionHelper.FromTitleId(npTicket.titleId); // Finally, convert it to GameVersion if (npTicket.GameVersion == GameVersion.Unknown) { - Logger.LogWarn($"Could not determine game version from title id {npTicket.titleId}", "Login"); + Logger.LogWarn($"Could not determine game version from title id {npTicket.titleId}", LogArea.Login); return null; } @@ -138,34 +138,35 @@ public class NPTicket if (npTicket.Platform == Platform.Unknown) { - Logger.LogWarn($"Could not determine platform from IssuerId {npTicket.IssuerId} decimal", "Login"); + Logger.LogWarn($"Could not determine platform from IssuerId {npTicket.IssuerId} decimal", LogArea.Login); return null; } #if DEBUG - Logger.LogDebug("npTicket data:", "Login"); - Logger.LogDebug(JsonSerializer.Serialize(npTicket), "Login"); + Logger.LogDebug("npTicket data:", LogArea.Login); + Logger.LogDebug(JsonSerializer.Serialize(npTicket), LogArea.Login); #endif return npTicket; } catch(NotImplementedException) { - Logger.LogError($"The ticket version {npTicket.ticketVersion} is not implemented yet.", "Login"); + Logger.LogError($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login); Logger.LogError ( "Please let us know that this is a ticket version that is actually used on our issue tracker at https://github.com/LBPUnion/project-lighthouse/issues !", - "Login" + LogArea.Login ); return null; } catch(Exception e) { - Logger.LogError("Failed to read npTicket!", "Login"); - Logger.LogError("Either this is spam data, or the more likely that this is a bug.", "Login"); - Logger.LogError("Please report the following exception to our issue tracker at https://github.com/LBPUnion/project-lighthouse/issues!", "Login"); - Logger.LogError(e.ToDetailedException(), "Login"); + Logger.LogError("Failed to read npTicket!", LogArea.Login); + Logger.LogError("Either this is spam data, or the more likely that this is a bug.", LogArea.Login); + Logger.LogError + ("Please report the following exception to our issue tracker at https://github.com/LBPUnion/project-lighthouse/issues!", LogArea.Login); + Logger.LogError(e.ToDetailedException(), LogArea.Login); return null; } }