Make logger a non-static class

This commit is contained in:
jvyden 2022-05-15 16:57:50 -04:00
parent c345eeebb9
commit 630b38e7bb
No known key found for this signature in database
GPG key ID: 18BCF2BE0262B278
27 changed files with 167 additions and 141 deletions

View file

@ -44,14 +44,14 @@ public class LoginController : ControllerBase
if (npTicket == null) if (npTicket == null)
{ {
Logger.LogWarn("npTicket was null, rejecting login", LogArea.Login); Logger.Warn("npTicket was null, rejecting login", LogArea.Login);
return this.BadRequest(); return this.BadRequest();
} }
IPAddress? remoteIpAddress = this.HttpContext.Connection.RemoteIpAddress; IPAddress? remoteIpAddress = this.HttpContext.Connection.RemoteIpAddress;
if (remoteIpAddress == null) 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 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); token = await this.database.AuthenticateUser(npTicket, ipAddress);
if (token == null) 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. return this.StatusCode(403, ""); // If not, then 403.
} }
} }
@ -76,7 +76,7 @@ public class LoginController : ControllerBase
if (user == null || user.Banned) 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, ""); return this.StatusCode(403, "");
} }
@ -109,11 +109,11 @@ public class LoginController : ControllerBase
if (!token.Approved) 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, ""); 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. // 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, // We just logged in with the token. Mark it as used so someone else doesnt try to use it,

View file

@ -46,7 +46,7 @@ public class MatchController : ControllerBase
if (bodyString.Length == 0 || bodyString[0] != '[') return this.BadRequest(); 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; IMatchCommand? matchData;
try try
@ -55,19 +55,19 @@ public class MatchController : ControllerBase
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while parsing matchData: ", LogArea.Match); Logger.Error("Exception while parsing matchData: ", LogArea.Match);
Logger.LogError(e.ToDetailedException(), LogArea.Match); Logger.Error(e.ToDetailedException(), LogArea.Match);
return this.BadRequest(); return this.BadRequest();
} }
if (matchData == null) 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(); 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 #endregion

View file

@ -98,7 +98,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.";
string scannedText = CensorHelper.ScanMessage(response); 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); return this.Ok(scannedText);
} }

View file

@ -64,7 +64,7 @@ public class PhotosController : ControllerBase
if (subject.User == null) continue; if (subject.User == null) continue;
subject.UserId = subject.User.UserId; 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); 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); // 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); this.database.Photos.Add(photo);

View file

@ -77,24 +77,24 @@ public class ResourcesController : ControllerBase
// lbp treats code 409 as success and as an indicator that the file is already present // lbp treats code 409 as success and as an indicator that the file is already present
if (FileHelper.ResourceExists(hash)) this.Conflict(); 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)); LbpFile file = new(await readFromPipeReader(this.Request.BodyReader));
if (!FileHelper.IsFileSafe(file)) 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(); return this.Conflict();
} }
string calculatedHash = file.Hash; string calculatedHash = file.Hash;
if (calculatedHash != 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); ($"File hash does not match the uploaded file! (hash: {hash}, calculatedHash: {calculatedHash}, type: {file.FileType})", LogArea.Resources);
return this.Conflict(); 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); await IOFile.WriteAllBytesAsync(path, file.Data);
return this.Ok(); return this.Ok();
} }

View file

@ -83,7 +83,7 @@ public class CollectionController : ControllerBase
Category? category = CategoryHelper.Categories.FirstOrDefault(c => c.Endpoint == endpointName); Category? category = CategoryHelper.Categories.FirstOrDefault(c => c.Endpoint == endpointName);
if (category == null) return this.NotFound(); if (category == null) return this.NotFound();
Logger.LogDebug("Found category " + category, LogArea.Category); Logger.Debug("Found category " + category, LogArea.Category);
List<Slot> slots; List<Slot> slots;
int totalSlots; int totalSlots;

View file

@ -51,7 +51,7 @@ public class GameServerStartup
if (string.IsNullOrEmpty(ServerConfiguration.Instance.DigestKey.PrimaryDigestKey)) 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. " + "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.", "To increase security, it is recommended that you find and set this variable.",

View file

@ -44,14 +44,14 @@ public class SlotPageController : ControllerBase
if (msg == null) 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); return this.Redirect("~/slot/" + id);
} }
msg = SanitizationHelper.SanitizeString(msg); msg = SanitizationHelper.SanitizeString(msg);
await this.database.PostComment(user, id, CommentType.Level, 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); return this.Redirect("~/slot/" + id);
} }

View file

@ -38,14 +38,14 @@ public class UserPageController : ControllerBase
if (msg == null) 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); return this.Redirect("~/user/" + id);
} }
msg = SanitizationHelper.SanitizeString(msg); msg = SanitizationHelper.SanitizeString(msg);
await this.database.PostComment(user, id, CommentType.Profile, 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); return this.Redirect("~/user/" + id);
} }

View file

@ -45,28 +45,28 @@ public class LoginForm : BaseLayout
User? user = await this.Database.Users.FirstOrDefaultAsync(u => u.Username == username); User? user = await this.Database.Users.FirstOrDefaultAsync(u => u.Username == username);
if (user == null) 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."; this.Error = "The username or password you entered is invalid.";
return this.Page(); return this.Page();
} }
if (!BCrypt.Net.BCrypt.Verify(password, user.Password)) 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."; this.Error = "The username or password you entered is invalid.";
return this.Page(); return this.Page();
} }
if (user.Banned) 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; this.Error = "You have been banned. Please contact an administrator for more information.\nReason: " + user.BannedReason;
return this.Page(); return this.Page();
} }
if (user.EmailAddress == null && ServerConfiguration.Instance.Mail.MailEnabled) 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() 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 (user.PasswordResetRequired) return this.Redirect("~/passwordResetRequired");
if (ServerConfiguration.Instance.Mail.MailEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail"); if (ServerConfiguration.Instance.Mail.MailEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail");

View file

@ -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); this.Database.WebTokens.Add(webToken);
await this.Database.SaveChangesAsync(); await this.Database.SaveChangesAsync();

View file

@ -22,17 +22,17 @@ public class CreateUserCommand : ICommand
if (user == null) if (user == null)
{ {
user = await this._database.CreateUser(onlineId, CryptoHelper.BCryptHash(password)); 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; 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(); await this._database.SaveChangesAsync();
Logger.LogInfo("Database changes saved.", LogArea.Database); Logger.Info("Database changes saved.", LogArea.Database);
} }
else else
{ {
Logger.LogError("A user with this username already exists.", LogArea.Login); Logger.Error("A user with this username already exists.", LogArea.Login);
} }
} }

View file

@ -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 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; ServerConfiguration? tempConfig;
@ -59,7 +59,7 @@ public class ServerConfiguration
if (Instance.ConfigVersion < CurrentConfigVersion) 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.ConfigVersion = CurrentConfigVersion;
Instance.writeConfig(ConfigFileName); 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. // If we have a valid legacy configuration we can migrate, let's do it now.
else if (File.Exists(LegacyConfigFileName)) else if (File.Exists(LegacyConfigFileName))
{ {
Logger.LogWarn("This version of Project Lighthouse now uses YML instead of JSON to store configuration.", LogArea.Config); Logger.Warn("This version of Project Lighthouse now uses YML instead of JSON to store configuration.", LogArea.Config);
Logger.LogWarn 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); ("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); LegacyServerSettings? legacyConfig = LegacyServerSettings.FromFile(LegacyConfigFileName);
Debug.Assert(legacyConfig != null); Debug.Assert(legacyConfig != null);
@ -79,7 +79,7 @@ public class ServerConfiguration
Instance.writeConfig(ConfigFileName); 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, // If there is no valid YML configuration available,
// generate a blank one and ask the server operator to configure it, then exit. // 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"); new ServerConfiguration().writeConfig(ConfigFileName + ".configme");
Logger.LogWarn Logger.Warn
( (
"The configuration file was not found. " + "The configuration file was not found. " +
"A blank configuration file has been created for you at " + "A blank configuration file has been created for you at " +
@ -101,7 +101,7 @@ public class ServerConfiguration
// Set up reloading // Set up reloading
if (Instance.ConfigReloading) if (Instance.ConfigReloading)
{ {
Logger.LogInfo("Setting up config reloading...", LogArea.Config); Logger.Info("Setting up config reloading...", LogArea.Config);
fileWatcher = new FileSystemWatcher fileWatcher = new FileSystemWatcher
{ {
Path = Environment.CurrentDirectory, Path = Environment.CurrentDirectory,
@ -119,19 +119,19 @@ public class ServerConfiguration
private static void onConfigChanged(object sender, FileSystemEventArgs e) private static void onConfigChanged(object sender, FileSystemEventArgs e)
{ {
Debug.Assert(e.Name == ConfigFileName); Debug.Assert(e.Name == ConfigFileName);
Logger.LogInfo("Configuration file modified, reloading config...", LogArea.Config); Logger.Info("Configuration file modified, reloading config...", LogArea.Config);
Logger.LogWarn("Some changes may not apply; they will require a restart of Lighthouse.", LogArea.Config); Logger.Warn("Some changes may not apply; they will require a restart of Lighthouse.", LogArea.Config);
ServerConfiguration? configuration = fromFile(ConfigFileName); ServerConfiguration? configuration = fromFile(ConfigFileName);
if (configuration == null) 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; return;
} }
Instance = configuration; Instance = configuration;
Logger.LogSuccess("Successfully reloaded the configuration!", LogArea.Config); Logger.Success("Successfully reloaded the configuration!", LogArea.Config);
} }
private static INamingConvention namingConvention = CamelCaseNamingConvention.Instance; private static INamingConvention namingConvention = CamelCaseNamingConvention.Instance;

View file

@ -19,7 +19,7 @@ public static class ServerStatics
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError(e.ToString(), LogArea.Database); Logger.Error(e.ToString(), LogArea.Database);
return false; return false;
} }
} }

View file

@ -11,13 +11,13 @@ public static class RedisConnectionExtensions
{ {
public static async Task RecreateIndexAsync(this IRedisConnection connection, Type type) 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 // TODO: use `await connection.DropIndexAndAssociatedRecordsAsync(type);` here instead when that becomes a thing
bool dropped = await connection.DropIndexAsync(type); 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); bool created = await connection.CreateIndexAsync(type);
Logger.LogDebug("Created index: " + created, LogArea.Redis); Logger.Debug("Created index: " + created, LogArea.Redis);
} }
} }

View file

@ -131,7 +131,7 @@ public static class FileHelper
EnsureDirectoryCreated(Path.Combine(Environment.CurrentDirectory, "png")); EnsureDirectoryCreated(Path.Combine(Environment.CurrentDirectory, "png"));
if (Directory.Exists("r")) 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<string> fileQueue = new(); ConcurrentQueue<string> fileQueue = new();

View file

@ -51,8 +51,8 @@ public static class InfluxHelper
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while logging: ", LogArea.InfluxDB); Logger.Error("Exception while logging: ", LogArea.InfluxDB);
Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); Logger.Error(e.ToDetailedException(), LogArea.InfluxDB);
} }
} }
@ -60,7 +60,7 @@ public static class InfluxHelper
public static async Task StartLogging() public static async Task StartLogging()
{ {
await Client.ReadyAsync(); await Client.ReadyAsync();
Logger.LogSuccess("InfluxDB is now ready.", LogArea.InfluxDB); Logger.Success("InfluxDB is now ready.", LogArea.InfluxDB);
Thread t = new Thread t = new
( (
delegate() delegate()
@ -73,8 +73,8 @@ public static class InfluxHelper
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while running log thread: ", LogArea.InfluxDB); Logger.Error("Exception while running log thread: ", LogArea.InfluxDB);
Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB); Logger.Error(e.ToDetailedException(), LogArea.InfluxDB);
} }
Thread.Sleep(60000); Thread.Sleep(60000);

View file

@ -29,7 +29,7 @@ public static class VersionHelper
} }
catch catch
{ {
Logger.LogError Logger.Error
( (
"Project Lighthouse was built incorrectly. Please make sure git is available when building. " + "Project Lighthouse was built incorrectly. Please make sure git is available when building. " +
"Because of this, you will not be notified of updates.", "Because of this, you will not be notified of updates.",
@ -42,7 +42,7 @@ public static class VersionHelper
if (IsDirty) if (IsDirty)
{ {
Logger.LogWarn Logger.Warn
( (
"This is a modified version of Project Lighthouse. " + "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.", "Please make sure you are properly disclosing the source code to any users who may be using this instance.",

View file

@ -13,7 +13,7 @@ public abstract class CategoryWithUser : Category
public override Slot? GetPreviewSlot(Database database) public override Slot? GetPreviewSlot(Database database)
{ {
#if DEBUG #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(); if (Debugger.IsAttached) Debugger.Break();
#endif #endif
return null; return null;
@ -23,7 +23,7 @@ public abstract class CategoryWithUser : Category
public override int GetTotalSlots(Database database) public override int GetTotalSlots(Database database)
{ {
#if DEBUG #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(); if (Debugger.IsAttached) Debugger.Break();
#endif #endif
return -1; return -1;
@ -33,7 +33,7 @@ public abstract class CategoryWithUser : Category
public override IEnumerable<Slot> GetSlots(Database database, int pageStart, int pageSize) public override IEnumerable<Slot> GetSlots(Database database, int pageStart, int pageSize)
{ {
#if DEBUG #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(); if (Debugger.IsAttached) Debugger.Break();
#endif #endif
return new List<Slot>(); return new List<Slot>();
@ -41,7 +41,7 @@ public abstract class CategoryWithUser : Category
public new string Serialize(Database database) 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; return string.Empty;
} }

View file

@ -16,30 +16,31 @@ namespace LBPUnion.ProjectLighthouse.Logging;
// logger.LogSuccess(); // logger.LogSuccess();
// I should also be able to access the log queue. // 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. // 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 #region Internals
/// <summary> /// <summary>
/// A list of custom loggers to use. /// A list of custom loggers to use.
/// </summary> /// </summary>
private static readonly List<ILogger> loggers = new(); private readonly List<ILogger> loggers = new();
public static void AddLogger(ILogger logger) public void AddLogger(ILogger logger)
{ {
loggers.Add(logger); loggers.Add(logger);
LogSuccess("Initialized " + logger.GetType().Name, LogArea.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 depth = 5;
const int skipDepth = depth - 2; const int skipDepth = depth - 2;
StackTrace stackTrace = new(true); StackTrace stackTrace = new(true);
StackFrame? frame = stackTrace.GetFrame(skipDepth + extraTraceLines); StackFrame? frame = stackTrace.GetFrame(skipDepth + extraTraceLines);
Debug.Assert(frame != null); System.Diagnostics.Debug.Assert(frame != null);
string? name; string? name;
string? section; 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. /// We use a queue because if two threads try to log something at the time they'll mess each other's printing up.
/// </para> /// </para>
/// </summary> /// </summary>
private static readonly ConcurrentQueue<LogLine> logQueue = new(); private readonly ConcurrentQueue<LogLine> logQueue = new();
/// <summary> /// <summary>
/// Adds a <see cref="LogLine"/> to the queue. Only used internally. /// Adds a <see cref="LogLine"/> to the queue. Only used internally.
/// </summary> /// </summary>
/// <param name="logLine">The logLine to send to the queue.</param> /// <param name="logLine">The logLine to send to the queue.</param>
private static void queueLog(LogLine logLine) private void queueLog(LogLine logLine)
{ {
logQueue.Enqueue(logLine); logQueue.Enqueue(logLine);
} }
[SuppressMessage("ReSharper", "FunctionNeverReturns")] [SuppressMessage("ReSharper", "FunctionNeverReturns")]
static Logger() // Start queue thread on first Logger access public Logger() // Start queue thread on first Logger access
{ {
Task.Factory.StartNew Task.Factory.StartNew
( (
@ -115,7 +116,7 @@ public static class Logger
/// Logs everything in the queue to all loggers immediately. /// 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. /// This is a helper function to allow for this function to be easily added to events.
/// </summary> /// </summary>
public static void Flush(object? _, EventArgs __) public void Flush(object? _, EventArgs __)
{ {
Flush(); Flush();
} }
@ -123,7 +124,7 @@ public static class Logger
/// <summary> /// <summary>
/// Logs everything in the queue to all loggers immediately. /// Logs everything in the queue to all loggers immediately.
/// </summary> /// </summary>
public static void Flush() public void Flush()
{ {
while (logQueue.TryDequeue(out LogLine line)) while (logQueue.TryDequeue(out LogLine line))
{ {
@ -138,7 +139,7 @@ public static class Logger
/// A function used by the queue thread /// A function used by the queue thread
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
private static bool queueLoop() private bool queueLoop()
{ {
bool logged = false; bool logged = false;
if (logQueue.TryDequeue(out LogLine line)) if (logQueue.TryDequeue(out LogLine line))
@ -157,48 +158,73 @@ public static class Logger
#endregion #endregion
#region Logging functions #region Logging functions
#region Static
public static void LogDebug(string text, LogArea logArea) public static void Debug(string text, LogArea logArea)
{ {
#if DEBUG #if DEBUG
Log(text, logArea.ToString(), LogLevel.Debug); Instance.Log(text, logArea.ToString(), LogLevel.Debug);
#endif #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 this.Log(text, logArea.ToString(), LogLevel.Success);
(
new LogLine
{
Level = level,
Message = text,
Area = area,
Trace = getTrace(extraTraceLines),
}
);
} }
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 #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
} }

View file

@ -21,10 +21,10 @@ public class AspNetToLighthouseLogger : Microsoft.Extensions.Logging.ILogger
{ {
LogLevel level = logLevel.ToLighthouseLevel(); 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; if (exception == null) return;
Logger.Log(exception.ToDetailedException(), this.Category, level, 4); Logger.Instance.Log(exception.ToDetailedException(), this.Category, level, 4);
} }
} }

View file

@ -41,7 +41,7 @@ public class RoomHelper
{ {
if (roomVersion == GameVersion.LittleBigPlanet1 || roomVersion == GameVersion.LittleBigPlanetPSP) 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; 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; return response;
} }
@ -163,7 +163,7 @@ public class RoomHelper
CleanupRooms(room.HostId, room); CleanupRooms(room.HostId, room);
lock(Rooms) Rooms.Add(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; return room;
} }
@ -234,7 +234,7 @@ public class RoomHelper
if (roomCountBeforeCleanup != roomCountAfterCleanup) if (roomCountBeforeCleanup != roomCountAfterCleanup)
{ {
Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", Logger.Debug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.",
LogArea.Match); LogArea.Match);
} }
} }

View file

@ -28,7 +28,7 @@ public class RequestLogMiddleware : Middleware
requestStopwatch.Stop(); requestStopwatch.Stop();
Logger.LogInfo Logger.Info
( (
$"{context.Response.StatusCode}, {requestStopwatch.ElapsedMilliseconds}ms: {context.Request.Method} {context.Request.Path}{context.Request.QueryString}", $"{context.Response.StatusCode}, {requestStopwatch.ElapsedMilliseconds}ms: {context.Request.Method} {context.Request.Path}{context.Request.QueryString}",
LogArea.HTTP LogArea.HTTP
@ -39,7 +39,7 @@ public class RequestLogMiddleware : Middleware
if (context.Request.Method == "POST") if (context.Request.Method == "POST")
{ {
context.Request.Body.Position = 0; 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 #endif
} }

View file

@ -49,18 +49,18 @@ public class DebugWarmupLifetime : IHostLifetime
url = url.Replace("0.0.0.0", "127.0.0.1"); 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 try
{ {
client.GetAsync(url).Wait(); client.GetAsync(url).Wait();
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogDebug("An error occurred while attempting to warm up hot reload. Initial page load will be delayed.", LogArea.Startup); Logger.Debug("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(e.ToDetailedException(), LogArea.Startup);
return; 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); public Task StopAsync(CancellationToken cancellationToken) => this.consoleLifetime.StopAsync(cancellationToken);

View file

@ -27,47 +27,47 @@ public static class StartupTasks
#endif #endif
// Setup logging // Setup logging
Logger.AddLogger(new ConsoleLogger()); Logger.Instance.AddLogger(new ConsoleLogger());
Logger.AddLogger(new LighthouseFileLogger()); Logger.Instance.AddLogger(new LighthouseFileLogger());
Logger.LogInfo($"Welcome to the Project Lighthouse {serverType.ToString()}!", LogArea.Startup); Logger.Info($"Welcome to the Project Lighthouse {serverType.ToString()}!", LogArea.Startup);
Logger.LogInfo($"You are running version {VersionHelper.FullVersion}", 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 // 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; bool dbConnected = ServerStatics.DbConnected;
if (!dbConnected) if (!dbConnected)
{ {
Logger.LogError("Database unavailable! Exiting.", LogArea.Startup); Logger.Error("Database unavailable! Exiting.", LogArea.Startup);
} }
else else
{ {
Logger.LogSuccess("Connected!", LogArea.Startup); Logger.Success("Connected!", LogArea.Startup);
} }
if (!dbConnected) Environment.Exit(1); if (!dbConnected) Environment.Exit(1);
using Database database = new(); using Database database = new();
Logger.LogInfo("Migrating database...", LogArea.Database); Logger.Info("Migrating database...", LogArea.Database);
migrateDatabase(database); migrateDatabase(database);
if (ServerConfiguration.Instance.InfluxDB.InfluxEnabled) 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(); 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! " + "This is a debug build, so performance may suffer! " +
"If you are running Lighthouse in a production environment, " + "If you are running Lighthouse in a production environment, " +
"it is highly recommended to run a release build. ", "it is highly recommended to run a release build. ",
LogArea.Startup 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) if (args.Length != 0)
{ {
@ -77,14 +77,14 @@ public static class StartupTasks
if (ServerConfiguration.Instance.WebsiteConfiguration.ConvertAssetsOnStartup) FileHelper.ConvertAllTexturesToPng(); 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(); RoomHelper.StartCleanupThread();
Logger.LogInfo("Initializing Redis...", LogArea.Startup); Logger.Info("Initializing Redis...", LogArea.Startup);
RedisDatabase.Initialize().Wait(); RedisDatabase.Initialize().Wait();
stopwatch.Stop(); 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) private static void migrateDatabase(Database database)
@ -95,6 +95,6 @@ public static class StartupTasks
database.Database.MigrateAsync().Wait(); database.Database.MigrateAsync().Wait();
stopwatch.Stop(); stopwatch.Stop();
Logger.LogSuccess($"Migration took {stopwatch.ElapsedMilliseconds}ms.", LogArea.Database); Logger.Success($"Migration took {stopwatch.ElapsedMilliseconds}ms.", LogArea.Database);
} }
} }

View file

@ -36,7 +36,7 @@ public static class RedisDatabase
string pong = (await connection.ExecuteAsync("PING")).ToString(CultureInfo.InvariantCulture); string pong = (await connection.ExecuteAsync("PING")).ToString(CultureInfo.InvariantCulture);
if (pong != "PONG") if (pong != "PONG")
{ {
Logger.LogError("Could not ping, ping returned " + pong, Logger.Error("Could not ping, ping returned " + pong,
LogArea.Redis); LogArea.Redis);
return; return;
} }
@ -46,17 +46,17 @@ public static class RedisDatabase
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Could not initialize Redis:\n" + e, LogArea.Redis); Logger.Error("Could not initialize Redis:\n" + e, LogArea.Redis);
return; return;
} }
Initialized = true; Initialized = true;
Logger.LogSuccess("Initialized Redis.", LogArea.Redis); Logger.Success("Initialized Redis.", LogArea.Redis);
} }
private static IRedisConnection getConnection() private static IRedisConnection getConnection()
{ {
Logger.LogDebug("Getting a Redis connection", LogArea.Redis); Logger.Debug("Getting a Redis connection", LogArea.Redis);
return provider.Connection; return provider.Connection;
} }

View file

@ -96,7 +96,7 @@ public class NPTicket
reader.ReadUInt16BE(); // Ticket length, we don't care about this reader.ReadUInt16BE(); // Ticket length, we don't care about this
SectionHeader bodyHeader = reader.ReadSectionHeader(); 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) 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 npTicket.titleId = npTicket.titleId.Substring(0, npTicket.titleId.Length - 3); // Trim _00 at the end
// Data now (hopefully): BCUS98245 // 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 npTicket.GameVersion = GameVersionHelper.FromTitleId(npTicket.titleId); // Finally, convert it to GameVersion
if (npTicket.GameVersion == GameVersion.Unknown) 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; return null;
} }
@ -141,21 +141,21 @@ public class NPTicket
if (npTicket.Platform == Platform.Unknown) 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; return null;
} }
#if DEBUG #if DEBUG
Logger.LogDebug("npTicket data:", LogArea.Login); Logger.Debug("npTicket data:", LogArea.Login);
Logger.LogDebug(JsonSerializer.Serialize(npTicket), LogArea.Login); Logger.Debug(JsonSerializer.Serialize(npTicket), LogArea.Login);
#endif #endif
return npTicket; return npTicket;
} }
catch(NotImplementedException) catch(NotImplementedException)
{ {
Logger.LogError($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login); Logger.Error($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login);
Logger.LogError 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 !", "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 LogArea.Login
@ -165,11 +165,11 @@ public class NPTicket
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Failed to read npTicket!", LogArea.Login); Logger.Error("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.Error("Either this is spam data, or the more likely that this is a bug.", LogArea.Login);
Logger.LogError Logger.Error
("Please report the following exception to our issue tracker at https://github.com/LBPUnion/project-lighthouse/issues!", LogArea.Login); ("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; return null;
} }
} }