diff --git a/ProjectLighthouse.Servers.GameServer/Controllers/LoginController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/LoginController.cs index e13fab24..270aa145 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/LoginController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/LoginController.cs @@ -44,14 +44,14 @@ public class LoginController : ControllerBase if (npTicket == null) { - Logger.LogWarn("npTicket was null, rejecting login", LogArea.Login); + Logger.Warn("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", LogArea.Login); + Logger.Warn("unable to determine ip, rejecting login", LogArea.Login); return this.StatusCode(403, ""); // 403 probably isnt the best status code for this, but whatever } @@ -67,7 +67,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}", LogArea.Login); + Logger.Warn($"Unable to find/generate a token for username {npTicket.Username}", LogArea.Login); return this.StatusCode(403, ""); // If not, then 403. } } @@ -76,7 +76,7 @@ public class LoginController : ControllerBase if (user == null || user.Banned) { - Logger.LogError($"Unable to find user {npTicket.Username} from token", LogArea.Login); + Logger.Error($"Unable to find user {npTicket.Username} from token", LogArea.Login); return this.StatusCode(403, ""); } @@ -109,11 +109,11 @@ public class LoginController : ControllerBase if (!token.Approved) { - Logger.LogWarn($"Token unapproved for user {user.Username}, rejecting login", LogArea.Login); + Logger.Warn($"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", LogArea.Login); + Logger.Success($"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.Servers.GameServer/Controllers/Matching/MatchController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/Matching/MatchController.cs index 70971f02..23a195a5 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/Matching/MatchController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/Matching/MatchController.cs @@ -46,7 +46,7 @@ public class MatchController : ControllerBase if (bodyString.Length == 0 || bodyString[0] != '[') return this.BadRequest(); - Logger.LogInfo("Received match data: " + bodyString, LogArea.Match); + Logger.Info("Received match data: " + bodyString, LogArea.Match); IMatchCommand? matchData; try @@ -55,19 +55,19 @@ public class MatchController : ControllerBase } catch(Exception e) { - Logger.LogError("Exception while parsing matchData: ", LogArea.Match); - Logger.LogError(e.ToDetailedException(), LogArea.Match); + Logger.Error("Exception while parsing matchData: ", LogArea.Match); + Logger.Error(e.ToDetailedException(), LogArea.Match); return this.BadRequest(); } if (matchData == null) { - Logger.LogError($"Could not parse match data: {nameof(matchData)} is null", LogArea.Match); + Logger.Error($"Could not parse match data: {nameof(matchData)} is null", LogArea.Match); return this.BadRequest(); } - Logger.LogInfo($"Parsed match from {user.Username} (type: {matchData.GetType()})", LogArea.Match); + Logger.Info($"Parsed match from {user.Username} (type: {matchData.GetType()})", LogArea.Match); #endregion diff --git a/ProjectLighthouse.Servers.GameServer/Controllers/MessageController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/MessageController.cs index b975ed75..63067c7a 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/MessageController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/MessageController.cs @@ -98,7 +98,7 @@ along with this program. If not, see ."; string scannedText = CensorHelper.ScanMessage(response); - Logger.LogInfo($"{user.Username}: {response} / {scannedText}", LogArea.Filter); + Logger.Info($"{user.Username}: {response} / {scannedText}", LogArea.Filter); return this.Ok(scannedText); } diff --git a/ProjectLighthouse.Servers.GameServer/Controllers/Resources/PhotosController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/Resources/PhotosController.cs index d2533dbd..f9461c8d 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/Resources/PhotosController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/Resources/PhotosController.cs @@ -64,7 +64,7 @@ public class PhotosController : ControllerBase if (subject.User == null) continue; subject.UserId = subject.User.UserId; - Logger.LogDebug($"Adding PhotoSubject (userid {subject.UserId}) to db", LogArea.Photos); + Logger.Debug($"Adding PhotoSubject (userid {subject.UserId}) to db", LogArea.Photos); this.database.PhotoSubjects.Add(subject); } @@ -84,7 +84,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", LogArea.Photos); + Logger.Debug($"Adding PhotoSubjectCollection ({photo.PhotoSubjectCollection}) to photo", LogArea.Photos); this.database.Photos.Add(photo); diff --git a/ProjectLighthouse.Servers.GameServer/Controllers/Resources/ResourcesController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/Resources/ResourcesController.cs index 006f6b6d..1ea40e45 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/Resources/ResourcesController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/Resources/ResourcesController.cs @@ -77,24 +77,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})", LogArea.Resources); + Logger.Info($"Processing resource upload (hash: {hash})", LogArea.Resources); LbpFile file = new(await readFromPipeReader(this.Request.BodyReader)); if (!FileHelper.IsFileSafe(file)) { - Logger.LogWarn($"File is unsafe (hash: {hash}, type: {file.FileType})", LogArea.Resources); + Logger.Warn($"File is unsafe (hash: {hash}, type: {file.FileType})", LogArea.Resources); return this.Conflict(); } string calculatedHash = file.Hash; if (calculatedHash != hash) { - Logger.LogWarn + Logger.Warn ($"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})", LogArea.Resources); + Logger.Success($"File is OK! (hash: {hash}, type: {file.FileType})", LogArea.Resources); await IOFile.WriteAllBytesAsync(path, file.Data); return this.Ok(); } diff --git a/ProjectLighthouse.Servers.GameServer/Controllers/Slots/CollectionController.cs b/ProjectLighthouse.Servers.GameServer/Controllers/Slots/CollectionController.cs index 1b6776c7..c6ce69db 100644 --- a/ProjectLighthouse.Servers.GameServer/Controllers/Slots/CollectionController.cs +++ b/ProjectLighthouse.Servers.GameServer/Controllers/Slots/CollectionController.cs @@ -83,7 +83,7 @@ public class CollectionController : ControllerBase Category? category = CategoryHelper.Categories.FirstOrDefault(c => c.Endpoint == endpointName); if (category == null) return this.NotFound(); - Logger.LogDebug("Found category " + category, LogArea.Category); + Logger.Debug("Found category " + category, LogArea.Category); List slots; int totalSlots; diff --git a/ProjectLighthouse.Servers.GameServer/Startup/GameServerStartup.cs b/ProjectLighthouse.Servers.GameServer/Startup/GameServerStartup.cs index f0340073..2c316e72 100644 --- a/ProjectLighthouse.Servers.GameServer/Startup/GameServerStartup.cs +++ b/ProjectLighthouse.Servers.GameServer/Startup/GameServerStartup.cs @@ -51,7 +51,7 @@ public class GameServerStartup if (string.IsNullOrEmpty(ServerConfiguration.Instance.DigestKey.PrimaryDigestKey)) { - Logger.LogWarn + Logger.Warn ( "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.", diff --git a/ProjectLighthouse.Servers.Website/Controllers/SlotPageController.cs b/ProjectLighthouse.Servers.Website/Controllers/SlotPageController.cs index 6886c116..414d9a0b 100644 --- a/ProjectLighthouse.Servers.Website/Controllers/SlotPageController.cs +++ b/ProjectLighthouse.Servers.Website/Controllers/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", LogArea.Comments); + Logger.Error($"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}", LogArea.Comments); + Logger.Success($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", LogArea.Comments); return this.Redirect("~/slot/" + id); } diff --git a/ProjectLighthouse.Servers.Website/Controllers/UserPageController.cs b/ProjectLighthouse.Servers.Website/Controllers/UserPageController.cs index 88a4a8f7..16b25782 100644 --- a/ProjectLighthouse.Servers.Website/Controllers/UserPageController.cs +++ b/ProjectLighthouse.Servers.Website/Controllers/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", LogArea.Comments); + Logger.Error($"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}", LogArea.Comments); + Logger.Success($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", LogArea.Comments); return this.Redirect("~/user/" + id); } diff --git a/ProjectLighthouse.Servers.Website/Pages/LoginForm.cshtml.cs b/ProjectLighthouse.Servers.Website/Pages/LoginForm.cshtml.cs index 4243fc1c..656a0bf7 100644 --- a/ProjectLighthouse.Servers.Website/Pages/LoginForm.cshtml.cs +++ b/ProjectLighthouse.Servers.Website/Pages/LoginForm.cshtml.cs @@ -45,28 +45,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", LogArea.Login); + Logger.Warn($"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", LogArea.Login); + Logger.Warn($"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", LogArea.Login); + Logger.Warn($"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 && ServerConfiguration.Instance.Mail.MailEnabled) { - Logger.LogWarn($"User {user.Username} (id: {user.UserId}) failed to login; email not set", LogArea.Login); + Logger.Warn($"User {user.Username} (id: {user.UserId}) failed to login; email not set", LogArea.Login); EmailSetToken emailSetToken = new() { @@ -100,7 +100,7 @@ public class LoginForm : BaseLayout } ); - Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web", LogArea.Login); + Logger.Success($"User {user.Username} (id: {user.UserId}) successfully logged in on web", LogArea.Login); if (user.PasswordResetRequired) return this.Redirect("~/passwordResetRequired"); if (ServerConfiguration.Instance.Mail.MailEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail"); diff --git a/ProjectLighthouse.Servers.Website/Pages/SetEmailForm.cshtml.cs b/ProjectLighthouse.Servers.Website/Pages/SetEmailForm.cshtml.cs index 2a21379e..05d57ee3 100644 --- a/ProjectLighthouse.Servers.Website/Pages/SetEmailForm.cshtml.cs +++ b/ProjectLighthouse.Servers.Website/Pages/SetEmailForm.cshtml.cs @@ -70,7 +70,7 @@ public class SetEmailForm : BaseLayout } ); - Logger.LogSuccess($"User {user.Username} (id: {user.UserId}) successfully logged in on web after setting an email address", LogArea.Login); + Logger.Success($"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/Administration/Maintenance/Commands/CreateUserCommand.cs b/ProjectLighthouse/Administration/Maintenance/Commands/CreateUserCommand.cs index dba2b60c..2d433e59 100644 --- a/ProjectLighthouse/Administration/Maintenance/Commands/CreateUserCommand.cs +++ b/ProjectLighthouse/Administration/Maintenance/Commands/CreateUserCommand.cs @@ -22,17 +22,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.", LogArea.Login); + Logger.Success($"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.", LogArea.Login); + Logger.Info("This user will need to reset their password when they log in.", LogArea.Login); await this._database.SaveChangesAsync(); - Logger.LogInfo("Database changes saved.", LogArea.Database); + Logger.Info("Database changes saved.", LogArea.Database); } else { - Logger.LogError("A user with this username already exists.", LogArea.Login); + Logger.Error("A user with this username already exists.", LogArea.Login); } } diff --git a/ProjectLighthouse/Configuration/ServerConfiguration.cs b/ProjectLighthouse/Configuration/ServerConfiguration.cs index 3b1abdb9..ddf8113b 100644 --- a/ProjectLighthouse/Configuration/ServerConfiguration.cs +++ b/ProjectLighthouse/Configuration/ServerConfiguration.cs @@ -47,7 +47,7 @@ public class ServerConfiguration { 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...", LogArea.Config); + Logger.Info("Loading config...", LogArea.Config); ServerConfiguration? tempConfig; @@ -59,7 +59,7 @@ public class ServerConfiguration if (Instance.ConfigVersion < CurrentConfigVersion) { - Logger.LogInfo($"Upgrading config file from version {Instance.ConfigVersion} to version {CurrentConfigVersion}", LogArea.Config); + Logger.Info($"Upgrading config file from version {Instance.ConfigVersion} to version {CurrentConfigVersion}", LogArea.Config); Instance.ConfigVersion = CurrentConfigVersion; Instance.writeConfig(ConfigFileName); @@ -68,10 +68,10 @@ public class ServerConfiguration // If we have a valid legacy configuration we can migrate, let's do it now. else if (File.Exists(LegacyConfigFileName)) { - Logger.LogWarn("This version of Project Lighthouse now uses YML instead of JSON to store configuration.", LogArea.Config); - Logger.LogWarn + Logger.Warn("This version of Project Lighthouse now uses YML instead of JSON to store configuration.", LogArea.Config); + Logger.Warn ("As such, the config will now be migrated to use YML. Do not modify the original JSON file; changes will not be kept.", LogArea.Config); - Logger.LogInfo($"The new configuration is stored at {ConfigFileName}.", LogArea.Config); + Logger.Info($"The new configuration is stored at {ConfigFileName}.", LogArea.Config); LegacyServerSettings? legacyConfig = LegacyServerSettings.FromFile(LegacyConfigFileName); Debug.Assert(legacyConfig != null); @@ -79,7 +79,7 @@ public class ServerConfiguration Instance.writeConfig(ConfigFileName); - Logger.LogSuccess("The configuration migration completed successfully.", LogArea.Config); + Logger.Success("The configuration migration completed successfully.", LogArea.Config); } // If there is no valid YML configuration available, // generate a blank one and ask the server operator to configure it, then exit. @@ -87,7 +87,7 @@ public class ServerConfiguration { new ServerConfiguration().writeConfig(ConfigFileName + ".configme"); - Logger.LogWarn + Logger.Warn ( "The configuration file was not found. " + "A blank configuration file has been created for you at " + @@ -101,7 +101,7 @@ public class ServerConfiguration // Set up reloading if (Instance.ConfigReloading) { - Logger.LogInfo("Setting up config reloading...", LogArea.Config); + Logger.Info("Setting up config reloading...", LogArea.Config); fileWatcher = new FileSystemWatcher { Path = Environment.CurrentDirectory, @@ -119,19 +119,19 @@ public class ServerConfiguration private static void onConfigChanged(object sender, FileSystemEventArgs e) { Debug.Assert(e.Name == ConfigFileName); - Logger.LogInfo("Configuration file modified, reloading config...", LogArea.Config); - Logger.LogWarn("Some changes may not apply; they will require a restart of Lighthouse.", LogArea.Config); + Logger.Info("Configuration file modified, reloading config...", LogArea.Config); + Logger.Warn("Some changes may not apply; they will require a restart of Lighthouse.", LogArea.Config); ServerConfiguration? configuration = fromFile(ConfigFileName); if (configuration == null) { - Logger.LogWarn("The new configuration was unable to be loaded for some reason. The old config has been kept.", LogArea.Config); + Logger.Warn("The new configuration was unable to be loaded for some reason. The old config has been kept.", LogArea.Config); return; } Instance = configuration; - Logger.LogSuccess("Successfully reloaded the configuration!", LogArea.Config); + Logger.Success("Successfully reloaded the configuration!", LogArea.Config); } private static INamingConvention namingConvention = CamelCaseNamingConvention.Instance; diff --git a/ProjectLighthouse/Configuration/ServerStatics.cs b/ProjectLighthouse/Configuration/ServerStatics.cs index cc75213e..233d0eba 100644 --- a/ProjectLighthouse/Configuration/ServerStatics.cs +++ b/ProjectLighthouse/Configuration/ServerStatics.cs @@ -19,7 +19,7 @@ public static class ServerStatics } catch(Exception e) { - Logger.LogError(e.ToString(), LogArea.Database); + Logger.Error(e.ToString(), LogArea.Database); return false; } } diff --git a/ProjectLighthouse/Extensions/RedisConnectionExtensions.cs b/ProjectLighthouse/Extensions/RedisConnectionExtensions.cs index 9211b5c0..8380d00c 100644 --- a/ProjectLighthouse/Extensions/RedisConnectionExtensions.cs +++ b/ProjectLighthouse/Extensions/RedisConnectionExtensions.cs @@ -11,13 +11,13 @@ public static class RedisConnectionExtensions { public static async Task RecreateIndexAsync(this IRedisConnection connection, Type type) { - Logger.LogDebug("Recreating index for " + type.Name, LogArea.Redis); + Logger.Debug("Recreating index for " + type.Name, LogArea.Redis); // TODO: use `await connection.DropIndexAndAssociatedRecordsAsync(type);` here instead when that becomes a thing bool dropped = await connection.DropIndexAsync(type); - Logger.LogDebug("Dropped index: " + dropped, LogArea.Redis); + Logger.Debug("Dropped index: " + dropped, LogArea.Redis); bool created = await connection.CreateIndexAsync(type); - Logger.LogDebug("Created index: " + created, LogArea.Redis); + Logger.Debug("Created index: " + created, LogArea.Redis); } } \ No newline at end of file diff --git a/ProjectLighthouse/Files/FileHelper.cs b/ProjectLighthouse/Files/FileHelper.cs index 3c2066f4..18a542fc 100644 --- a/ProjectLighthouse/Files/FileHelper.cs +++ b/ProjectLighthouse/Files/FileHelper.cs @@ -131,7 +131,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...", LogArea.Startup); + Logger.Info("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 a9266390..7895853a 100644 --- a/ProjectLighthouse/Helpers/InfluxHelper.cs +++ b/ProjectLighthouse/Helpers/InfluxHelper.cs @@ -51,8 +51,8 @@ public static class InfluxHelper } catch(Exception e) { - Logger.LogError("Exception while logging: ", LogArea.InfluxDB); - Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); + Logger.Error("Exception while logging: ", LogArea.InfluxDB); + Logger.Error(e.ToDetailedException(), LogArea.InfluxDB); } } @@ -60,7 +60,7 @@ public static class InfluxHelper public static async Task StartLogging() { await Client.ReadyAsync(); - Logger.LogSuccess("InfluxDB is now ready.", LogArea.InfluxDB); + Logger.Success("InfluxDB is now ready.", LogArea.InfluxDB); Thread t = new ( delegate() @@ -73,8 +73,8 @@ public static class InfluxHelper } catch(Exception e) { - Logger.LogError("Exception while running log thread: ", LogArea.InfluxDB); - Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); + Logger.Error("Exception while running log thread: ", LogArea.InfluxDB); + Logger.Error(e.ToDetailedException(), LogArea.InfluxDB); } Thread.Sleep(60000); diff --git a/ProjectLighthouse/Helpers/VersionHelper.cs b/ProjectLighthouse/Helpers/VersionHelper.cs index 84b67711..3642c5fe 100644 --- a/ProjectLighthouse/Helpers/VersionHelper.cs +++ b/ProjectLighthouse/Helpers/VersionHelper.cs @@ -29,7 +29,7 @@ public static class VersionHelper } catch { - Logger.LogError + Logger.Error ( "Project Lighthouse was built incorrectly. Please make sure git is available when building. " + "Because of this, you will not be notified of updates.", @@ -42,7 +42,7 @@ public static class VersionHelper if (IsDirty) { - Logger.LogWarn + Logger.Warn ( "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.", diff --git a/ProjectLighthouse/Levels/Categories/CategoryWithUser.cs b/ProjectLighthouse/Levels/Categories/CategoryWithUser.cs index ae2a2281..893d32a1 100644 --- a/ProjectLighthouse/Levels/Categories/CategoryWithUser.cs +++ b/ProjectLighthouse/Levels/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", LogArea.Category); + Logger.Error("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", LogArea.Category); + Logger.Error("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", LogArea.Category); + Logger.Error("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", LogArea.Category); + Logger.Error("tried to serialize without user on CategoryWithUser", LogArea.Category); return string.Empty; } diff --git a/ProjectLighthouse/Logging/Logger.cs b/ProjectLighthouse/Logging/Logger.cs index 5af2deb0..0078d464 100644 --- a/ProjectLighthouse/Logging/Logger.cs +++ b/ProjectLighthouse/Logging/Logger.cs @@ -16,30 +16,31 @@ namespace LBPUnion.ProjectLighthouse.Logging; // logger.LogSuccess(); // I should also be able to access the log queue. // This functionality is going to be used in the admin panel to get the output of commands. -public static class Logger +public class Logger { - + internal static readonly Logger Instance = new(); + #region Internals /// /// A list of custom loggers to use. /// - private static readonly List loggers = new(); + private readonly List loggers = new(); - public static void AddLogger(ILogger logger) + public void AddLogger(ILogger logger) { loggers.Add(logger); LogSuccess("Initialized " + logger.GetType().Name, LogArea.Logger); } - private static LogTrace getTrace(int extraTraceLines = 0) + private LogTrace getTrace(int extraTraceLines = 0) { const int depth = 5; const int skipDepth = depth - 2; StackTrace stackTrace = new(true); StackFrame? frame = stackTrace.GetFrame(skipDepth + extraTraceLines); - Debug.Assert(frame != null); + System.Diagnostics.Debug.Assert(frame != null); string? name; string? section; @@ -76,19 +77,19 @@ public static class Logger /// We use a queue because if two threads try to log something at the time they'll mess each other's printing up. /// /// - private static readonly ConcurrentQueue logQueue = new(); + private readonly ConcurrentQueue logQueue = new(); /// /// Adds a to the queue. Only used internally. /// /// The logLine to send to the queue. - private static void queueLog(LogLine logLine) + private void queueLog(LogLine logLine) { logQueue.Enqueue(logLine); } [SuppressMessage("ReSharper", "FunctionNeverReturns")] - static Logger() // Start queue thread on first Logger access + public Logger() // Start queue thread on first Logger access { Task.Factory.StartNew ( @@ -115,7 +116,7 @@ public static class Logger /// Logs everything in the queue to all loggers immediately. /// This is a helper function to allow for this function to be easily added to events. /// - public static void Flush(object? _, EventArgs __) + public void Flush(object? _, EventArgs __) { Flush(); } @@ -123,7 +124,7 @@ public static class Logger /// /// Logs everything in the queue to all loggers immediately. /// - public static void Flush() + public void Flush() { while (logQueue.TryDequeue(out LogLine line)) { @@ -138,7 +139,7 @@ public static class Logger /// A function used by the queue thread /// /// - private static bool queueLoop() + private bool queueLoop() { bool logged = false; if (logQueue.TryDequeue(out LogLine line)) @@ -157,48 +158,73 @@ public static class Logger #endregion #region Logging functions - - public static void LogDebug(string text, LogArea logArea) + #region Static + public static void Debug(string text, LogArea logArea) { #if DEBUG - Log(text, logArea.ToString(), LogLevel.Debug); + Instance.Log(text, logArea.ToString(), LogLevel.Debug); #endif } - public static void LogSuccess(string text, LogArea logArea) + public static void Success(string text, LogArea logArea) { - Log(text, logArea.ToString(), LogLevel.Success); + Instance.Log(text, logArea.ToString(), LogLevel.Success); } - public static void LogInfo(string text, LogArea logArea) + public static void Info(string text, LogArea logArea) { - Log(text, logArea.ToString(), LogLevel.Info); + Instance.Log(text, logArea.ToString(), LogLevel.Info); } - public static void LogWarn(string text, LogArea logArea) + public static void Warn(string text, LogArea logArea) { - Log(text, logArea.ToString(), LogLevel.Warning); + Instance.Log(text, logArea.ToString(), LogLevel.Warning); } - public static void LogError(string text, LogArea logArea) + public static void Error(string text, LogArea logArea) { - Log(text, logArea.ToString(), LogLevel.Error); + Instance.Log(text, logArea.ToString(), LogLevel.Error); + } + + #endregion + #region Instance-based + public void LogDebug(string text, LogArea logArea) + { + #if DEBUG + this.Log(text, logArea.ToString(), LogLevel.Debug); + #endif } - public static void Log(string text, string area, LogLevel level, int extraTraceLines = 0) + public void LogSuccess(string text, LogArea logArea) { - queueLog - ( - new LogLine - { - Level = level, - Message = text, - Area = area, - Trace = getTrace(extraTraceLines), - } - ); + this.Log(text, logArea.ToString(), LogLevel.Success); } + public void LogInfo(string text, LogArea logArea) + { + this.Log(text, logArea.ToString(), LogLevel.Info); + } + + public void LogWarn(string text, LogArea logArea) + { + this.Log(text, logArea.ToString(), LogLevel.Warning); + } + + public void LogError(string text, LogArea logArea) + { + this.Log(text, logArea.ToString(), LogLevel.Error); + } #endregion + public void Log(string text, string area, LogLevel level, int extraTraceLines = 0) + { + queueLog(new LogLine + { + Level = level, + Message = text, + Area = area, + Trace = getTrace(extraTraceLines), + }); + } + #endregion } \ No newline at end of file diff --git a/ProjectLighthouse/Logging/Loggers/AspNet/AspNetToLighthouseLogger.cs b/ProjectLighthouse/Logging/Loggers/AspNet/AspNetToLighthouseLogger.cs index a26a5cce..70820141 100644 --- a/ProjectLighthouse/Logging/Loggers/AspNet/AspNetToLighthouseLogger.cs +++ b/ProjectLighthouse/Logging/Loggers/AspNet/AspNetToLighthouseLogger.cs @@ -21,10 +21,10 @@ public class AspNetToLighthouseLogger : Microsoft.Extensions.Logging.ILogger { LogLevel level = logLevel.ToLighthouseLevel(); - Logger.Log(state.ToString(), this.Category, level, 4); + Logger.Instance.Log(state.ToString(), this.Category, level, 4); if (exception == null) return; - Logger.Log(exception.ToDetailedException(), this.Category, level, 4); + Logger.Instance.Log(exception.ToDetailedException(), this.Category, level, 4); } } \ No newline at end of file diff --git a/ProjectLighthouse/Match/Rooms/RoomHelper.cs b/ProjectLighthouse/Match/Rooms/RoomHelper.cs index 1bf04469..9d4f18e4 100644 --- a/ProjectLighthouse/Match/Rooms/RoomHelper.cs +++ b/ProjectLighthouse/Match/Rooms/RoomHelper.cs @@ -41,7 +41,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?)", LogArea.Match); + Logger.Error($"Returning null for FindBestRoom, game ({roomVersion}) does not support dive in (should never happen?)", LogArea.Match); return null; } @@ -130,7 +130,7 @@ public class RoomHelper }, }; - Logger.LogSuccess($"Found a room (id: {room.RoomId}) for user {user?.Username ?? "null"} (id: {user?.UserId ?? -1})", LogArea.Match); + Logger.Success($"Found a room (id: {room.RoomId}) for user {user?.Username ?? "null"} (id: {user?.UserId ?? -1})", LogArea.Match); return response; } @@ -163,7 +163,7 @@ public class RoomHelper CleanupRooms(room.HostId, room); lock(Rooms) Rooms.Add(room); - Logger.LogInfo($"Created room (id: {room.RoomId}) for host {room.HostId}", LogArea.Match); + Logger.Info($"Created room (id: {room.RoomId}) for host {room.HostId}", LogArea.Match); return room; } @@ -234,7 +234,7 @@ public class RoomHelper if (roomCountBeforeCleanup != roomCountAfterCleanup) { - Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", + Logger.Debug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", LogArea.Match); } } diff --git a/ProjectLighthouse/Middlewares/RequestLogMiddleware.cs b/ProjectLighthouse/Middlewares/RequestLogMiddleware.cs index 25361a00..95998082 100644 --- a/ProjectLighthouse/Middlewares/RequestLogMiddleware.cs +++ b/ProjectLighthouse/Middlewares/RequestLogMiddleware.cs @@ -28,7 +28,7 @@ public class RequestLogMiddleware : Middleware requestStopwatch.Stop(); - Logger.LogInfo + Logger.Info ( $"{context.Response.StatusCode}, {requestStopwatch.ElapsedMilliseconds}ms: {context.Request.Method} {context.Request.Path}{context.Request.QueryString}", LogArea.HTTP @@ -39,7 +39,7 @@ public class RequestLogMiddleware : Middleware if (context.Request.Method == "POST") { context.Request.Body.Position = 0; - Logger.LogDebug(await new StreamReader(context.Request.Body).ReadToEndAsync(), LogArea.HTTP); + Logger.Debug(await new StreamReader(context.Request.Body).ReadToEndAsync(), LogArea.HTTP); } #endif } diff --git a/ProjectLighthouse/Startup/DebugWarmupLifetime.cs b/ProjectLighthouse/Startup/DebugWarmupLifetime.cs index 9a0db149..2cbef0fd 100644 --- a/ProjectLighthouse/Startup/DebugWarmupLifetime.cs +++ b/ProjectLighthouse/Startup/DebugWarmupLifetime.cs @@ -49,18 +49,18 @@ public class DebugWarmupLifetime : IHostLifetime url = url.Replace("0.0.0.0", "127.0.0.1"); - Logger.LogDebug("Warming up Hot Reload...", LogArea.Startup); + Logger.Debug("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.", LogArea.Startup); - Logger.LogDebug(e.ToDetailedException(), LogArea.Startup); + Logger.Debug("An error occurred while attempting to warm up hot reload. Initial page load will be delayed.", LogArea.Startup); + Logger.Debug(e.ToDetailedException(), LogArea.Startup); return; } - Logger.LogSuccess("Hot Reload is ready to go!", LogArea.Startup); + Logger.Success("Hot Reload is ready to go!", LogArea.Startup); } public Task StopAsync(CancellationToken cancellationToken) => this.consoleLifetime.StopAsync(cancellationToken); diff --git a/ProjectLighthouse/StartupTasks.cs b/ProjectLighthouse/StartupTasks.cs index 627b0de7..50165011 100644 --- a/ProjectLighthouse/StartupTasks.cs +++ b/ProjectLighthouse/StartupTasks.cs @@ -27,47 +27,47 @@ public static class StartupTasks #endif // Setup logging - Logger.AddLogger(new ConsoleLogger()); - Logger.AddLogger(new LighthouseFileLogger()); + Logger.Instance.AddLogger(new ConsoleLogger()); + Logger.Instance.AddLogger(new LighthouseFileLogger()); - Logger.LogInfo($"Welcome to the Project Lighthouse {serverType.ToString()}!", LogArea.Startup); - Logger.LogInfo($"You are running version {VersionHelper.FullVersion}", LogArea.Startup); + Logger.Info($"Welcome to the Project Lighthouse {serverType.ToString()}!", LogArea.Startup); + Logger.Info($"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 " + ServerConfiguration.Instance.ConfigVersion, LogArea.Startup); + Logger.Success("Loaded config file version " + ServerConfiguration.Instance.ConfigVersion, LogArea.Startup); - Logger.LogInfo("Connecting to the database...", LogArea.Startup); + Logger.Info("Connecting to the database...", LogArea.Startup); bool dbConnected = ServerStatics.DbConnected; if (!dbConnected) { - Logger.LogError("Database unavailable! Exiting.", LogArea.Startup); + Logger.Error("Database unavailable! Exiting.", LogArea.Startup); } else { - Logger.LogSuccess("Connected!", LogArea.Startup); + Logger.Success("Connected!", LogArea.Startup); } if (!dbConnected) Environment.Exit(1); using Database database = new(); - Logger.LogInfo("Migrating database...", LogArea.Database); + Logger.Info("Migrating database...", LogArea.Database); migrateDatabase(database); if (ServerConfiguration.Instance.InfluxDB.InfluxEnabled) { - Logger.LogInfo("Influx logging is enabled. Starting influx logging...", LogArea.Startup); + Logger.Info("Influx logging is enabled. Starting influx logging...", LogArea.Startup); InfluxHelper.StartLogging().Wait(); - if (ServerConfiguration.Instance.InfluxDB.LoggingEnabled) Logger.AddLogger(new InfluxLogger()); + if (ServerConfiguration.Instance.InfluxDB.LoggingEnabled) Logger.Instance.AddLogger(new InfluxLogger()); } - Logger.LogDebug + Logger.Debug ( "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. ", LogArea.Startup ); - Logger.LogDebug("You can do so by running any dotnet command with the flag: \"-c Release\". ", LogArea.Startup); + Logger.Debug("You can do so by running any dotnet command with the flag: \"-c Release\". ", LogArea.Startup); if (args.Length != 0) { @@ -77,14 +77,14 @@ public static class StartupTasks if (ServerConfiguration.Instance.WebsiteConfiguration.ConvertAssetsOnStartup) FileHelper.ConvertAllTexturesToPng(); - Logger.LogInfo("Starting room cleanup thread...", LogArea.Startup); + Logger.Info("Starting room cleanup thread...", LogArea.Startup); RoomHelper.StartCleanupThread(); - Logger.LogInfo("Initializing Redis...", LogArea.Startup); + Logger.Info("Initializing Redis...", LogArea.Startup); RedisDatabase.Initialize().Wait(); stopwatch.Stop(); - Logger.LogSuccess($"Ready! Startup took {stopwatch.ElapsedMilliseconds}ms. Passing off control to ASP.NET...", LogArea.Startup); + Logger.Success($"Ready! Startup took {stopwatch.ElapsedMilliseconds}ms. Passing off control to ASP.NET...", LogArea.Startup); } private static void migrateDatabase(Database database) @@ -95,6 +95,6 @@ public static class StartupTasks database.Database.MigrateAsync().Wait(); stopwatch.Stop(); - Logger.LogSuccess($"Migration took {stopwatch.ElapsedMilliseconds}ms.", LogArea.Database); + Logger.Success($"Migration took {stopwatch.ElapsedMilliseconds}ms.", LogArea.Database); } } \ No newline at end of file diff --git a/ProjectLighthouse/StorableLists/RedisDatabase.cs b/ProjectLighthouse/StorableLists/RedisDatabase.cs index c4c7583b..e219b1e3 100644 --- a/ProjectLighthouse/StorableLists/RedisDatabase.cs +++ b/ProjectLighthouse/StorableLists/RedisDatabase.cs @@ -36,7 +36,7 @@ public static class RedisDatabase string pong = (await connection.ExecuteAsync("PING")).ToString(CultureInfo.InvariantCulture); if (pong != "PONG") { - Logger.LogError("Could not ping, ping returned " + pong, + Logger.Error("Could not ping, ping returned " + pong, LogArea.Redis); return; } @@ -46,17 +46,17 @@ public static class RedisDatabase } catch(Exception e) { - Logger.LogError("Could not initialize Redis:\n" + e, LogArea.Redis); + Logger.Error("Could not initialize Redis:\n" + e, LogArea.Redis); return; } Initialized = true; - Logger.LogSuccess("Initialized Redis.", LogArea.Redis); + Logger.Success("Initialized Redis.", LogArea.Redis); } private static IRedisConnection getConnection() { - Logger.LogDebug("Getting a Redis connection", LogArea.Redis); + Logger.Debug("Getting a Redis connection", LogArea.Redis); return provider.Connection; } diff --git a/ProjectLighthouse/Tickets/NPTicket.cs b/ProjectLighthouse/Tickets/NPTicket.cs index bacb558f..84fa0723 100644 --- a/ProjectLighthouse/Tickets/NPTicket.cs +++ b/ProjectLighthouse/Tickets/NPTicket.cs @@ -96,7 +96,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}", LogArea.Login); + Logger.Debug($"bodyHeader.Type is {bodyHeader.Type}", LogArea.Login); switch (npTicket.ticketVersion) { @@ -118,13 +118,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}", LogArea.Login); + Logger.Debug($"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}", LogArea.Login); + Logger.Warn($"Could not determine game version from title id {npTicket.titleId}", LogArea.Login); return null; } @@ -141,21 +141,21 @@ public class NPTicket if (npTicket.Platform == Platform.Unknown) { - Logger.LogWarn($"Could not determine platform from IssuerId {npTicket.IssuerId} decimal", LogArea.Login); + Logger.Warn($"Could not determine platform from IssuerId {npTicket.IssuerId} decimal", LogArea.Login); return null; } #if DEBUG - Logger.LogDebug("npTicket data:", LogArea.Login); - Logger.LogDebug(JsonSerializer.Serialize(npTicket), LogArea.Login); + Logger.Debug("npTicket data:", LogArea.Login); + Logger.Debug(JsonSerializer.Serialize(npTicket), LogArea.Login); #endif return npTicket; } catch(NotImplementedException) { - Logger.LogError($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login); - Logger.LogError + Logger.Error($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login); + Logger.Error ( "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 !", LogArea.Login @@ -165,11 +165,11 @@ public class NPTicket } catch(Exception e) { - 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 + Logger.Error("Failed to read npTicket!", LogArea.Login); + Logger.Error("Either this is spam data, or the more likely that this is a bug.", LogArea.Login); + Logger.Error ("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); + Logger.Error(e.ToDetailedException(), LogArea.Login); return null; } }