Make internal logging use an enum instead of a string for areas

This commit is contained in:
jvyden 2022-05-01 18:34:26 -04:00
commit 55160ff434
No known key found for this signature in database
GPG key ID: 18BCF2BE0262B278
24 changed files with 123 additions and 100 deletions

View file

@ -45,14 +45,14 @@ public class LoginController : ControllerBase
if (npTicket == null) if (npTicket == null)
{ {
Logger.LogWarn("npTicket was null, rejecting login", "Login"); Logger.LogWarn("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", "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 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); 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}", "Login"); Logger.LogWarn($"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.
} }
} }
@ -77,7 +77,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", "Login"); Logger.LogError($"Unable to find user {npTicket.Username} from token", LogArea.Login);
return this.StatusCode(403, ""); return this.StatusCode(403, "");
} }
@ -94,7 +94,7 @@ public class LoginController : ControllerBase
DeniedAuthenticationHelper.AddAttempt(ipAddressAndName); DeniedAuthenticationHelper.AddAttempt(ipAddressAndName);
await this.database.SaveChangesAsync(); 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, ""); return this.StatusCode(403, "");
} }
} }
@ -126,11 +126,11 @@ public class LoginController : ControllerBase
if (!token.Approved) 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, ""); 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. // 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

@ -47,7 +47,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, "Match"); Logger.LogInfo("Received match data: " + bodyString, LogArea.Match);
IMatchData? matchData; IMatchData? matchData;
try try
@ -56,19 +56,19 @@ public class MatchController : ControllerBase
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while parsing matchData: ", "Match"); Logger.LogError("Exception while parsing matchData: ", LogArea.Match);
Logger.LogError(e.ToDetailedException(), "Match"); Logger.LogError(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", "Match"); Logger.LogError($"Could not parse match data: {nameof(matchData)} is null", LogArea.Match);
return this.BadRequest(); 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 #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}", "Filter"); Logger.LogInfo($"{user.Username}: {response} / {scannedText}", LogArea.Filter);
return this.Ok(scannedText); return this.Ok(scannedText);
} }

View file

@ -67,7 +67,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", "Photos"); Logger.LogDebug($"Adding PhotoSubject (userid {subject.UserId}) to db", LogArea.Photos);
this.database.PhotoSubjects.Add(subject); 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); // 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); this.database.Photos.Add(photo);

View file

@ -96,23 +96,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})", "Resources"); Logger.LogInfo($"Processing resource upload (hash: {hash})", LogArea.Resources);
LbpFile file = new(await BinaryHelper.ReadFromPipeReader(this.Request.BodyReader)); LbpFile file = new(await BinaryHelper.ReadFromPipeReader(this.Request.BodyReader));
if (!FileHelper.IsFileSafe(file)) 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(); return this.Conflict();
} }
string calculatedHash = file.Hash; string calculatedHash = file.Hash;
if (calculatedHash != 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(); 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); await IOFile.WriteAllBytesAsync(path, file.Data);
return this.Ok(); return this.Ok();
} }

View file

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

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", "Comments"); Logger.LogError($"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}", "Comments"); Logger.LogSuccess($"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", "Comments"); Logger.LogError($"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}", "Comments"); Logger.LogSuccess($"Posted comment from {user.UserId}: \"{msg}\" on user {id}", LogArea.Comments);
return this.Redirect("~/user/" + id); return this.Redirect("~/user/" + id);
} }

View file

@ -114,7 +114,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...", "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<string> fileQueue = new(); ConcurrentQueue<string> fileQueue = new();

View file

@ -49,8 +49,8 @@ public static class InfluxHelper
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while logging: ", "InfluxDB"); Logger.LogError("Exception while logging: ", LogArea.InfluxDB);
Logger.LogError(e.ToDetailedException(), "InfluxDB"); Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB);
} }
} }
@ -58,7 +58,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.", "InfluxDB"); Logger.LogSuccess("InfluxDB is now ready.", LogArea.InfluxDB);
Thread t = new Thread t = new
( (
delegate() delegate()
@ -71,8 +71,8 @@ public static class InfluxHelper
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Exception while running log thread: ", "InfluxDB"); Logger.LogError("Exception while running log thread: ", LogArea.InfluxDB);
Logger.LogError(e.ToDetailedException(), "InfluxDB"); Logger.LogError(e.ToDetailedException(), LogArea.InfluxDB);
} }
Thread.Sleep(60000); Thread.Sleep(60000);

View file

@ -45,7 +45,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?)", "Match"); Logger.LogError($"Returning null for FindBestRoom, game ({roomVersion}) does not support dive in (should never happen?)", LogArea.Match);
return null; 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; return response;
} }
@ -172,7 +172,7 @@ public class RoomHelper
CleanupRooms(room.Host, room); CleanupRooms(room.Host, room);
lock(Rooms) Rooms.Add(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; return room;
} }
@ -237,7 +237,7 @@ public class RoomHelper
if (roomCountBeforeCleanup != roomCountAfterCleanup) if (roomCountBeforeCleanup != roomCountAfterCleanup)
{ {
Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", "Match"); Logger.LogDebug($"Cleaned up {roomCountBeforeCleanup - roomCountAfterCleanup} rooms.", LogArea.Match);
} }
} }
} }

View file

@ -33,7 +33,7 @@ public static class VersionHelper
( (
"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.",
"Startup" LogArea.Startup
); );
CommitHash = "invalid"; CommitHash = "invalid";
Branch = "invalid"; Branch = "invalid";
@ -46,7 +46,7 @@ public static class VersionHelper
( (
"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.",
"Startup" LogArea.Startup
); );
CanCheckForUpdates = false; CanCheckForUpdates = false;
} }

View file

@ -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,
}

View file

@ -28,7 +28,7 @@ public static class Logger
public static void AddLogger(ILogger logger) public static void AddLogger(ILogger logger)
{ {
loggers.Add(logger); loggers.Add(logger);
LogSuccess("Initialized " + logger.GetType().Name, "Logger"); LogSuccess("Initialized " + logger.GetType().Name, LogArea.Logger);
} }
private static LogTrace getTrace(int extraTraceLines = 0) private static LogTrace getTrace(int extraTraceLines = 0)
@ -144,31 +144,31 @@ public static class Logger
#region Logging functions #region Logging functions
public static void LogDebug(string text, string area = "") public static void LogDebug(string text, LogArea logArea)
{ {
#if DEBUG #if DEBUG
Log(text, area, LogLevel.Debug); Log(text, logArea.ToString(), LogLevel.Debug);
#endif #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) public static void Log(string text, string area, LogLevel level, int extraTraceLines = 0)

View file

@ -24,17 +24,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.", "Login"); Logger.LogSuccess($"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.", "Login"); Logger.LogInfo("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.", "Database"); Logger.LogInfo("Database changes saved.", LogArea.Database);
} }
else else
{ {
Logger.LogError("A user with this username already exists.", "Login"); Logger.LogError("A user with this username already exists.", LogArea.Login);
} }
} }

View file

@ -46,28 +46,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", "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."; 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", "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."; 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", "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; 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 && ServerSettings.Instance.SMTPEnabled) 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() 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 (user.PasswordResetRequired) return this.Redirect("~/passwordResetRequired");
if (ServerSettings.Instance.SMTPEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail"); if (ServerSettings.Instance.SMTPEnabled && !user.EmailAddressVerified) return this.Redirect("~/login/sendVerificationEmail");

View file

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

View file

@ -27,32 +27,32 @@ public static class Program
Logger.AddLogger(new ConsoleLogger()); Logger.AddLogger(new ConsoleLogger());
Logger.AddLogger(new LighthouseFileLogger()); Logger.AddLogger(new LighthouseFileLogger());
Logger.LogInfo("Welcome to Project Lighthouse!", "Startup"); Logger.LogInfo("Welcome to Project Lighthouse!", LogArea.Startup);
Logger.LogInfo($"You are running version {VersionHelper.FullVersion}", "Startup"); Logger.LogInfo($"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 " + 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; bool dbConnected = ServerStatics.DbConnected;
if (!dbConnected) if (!dbConnected)
{ {
Logger.LogError("Database unavailable! Exiting.", "Startup"); Logger.LogError("Database unavailable! Exiting.", LogArea.Startup);
} }
else else
{ {
Logger.LogSuccess("Connected to the database.", "Startup"); Logger.LogSuccess("Connected to the database.", LogArea.Startup);
} }
if (!dbConnected) Environment.Exit(1); if (!dbConnected) Environment.Exit(1);
using Database database = new(); using Database database = new();
Logger.LogInfo("Migrating database...", "Database"); Logger.LogInfo("Migrating database...", LogArea.Database);
MigrateDatabase(database); MigrateDatabase(database);
if (ServerSettings.Instance.InfluxEnabled) 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(); InfluxHelper.StartLogging().Wait();
if (ServerSettings.Instance.InfluxLoggingEnabled) Logger.AddLogger(new InfluxLogger()); 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! " + "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. ",
"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) if (args.Length != 0)
{ {
@ -74,11 +74,11 @@ public static class Program
if (ServerSettings.Instance.ConvertAssetsOnStartup) FileHelper.ConvertAllTexturesToPng(); if (ServerSettings.Instance.ConvertAssetsOnStartup) FileHelper.ConvertAllTexturesToPng();
Logger.LogInfo("Starting room cleanup thread...", "Startup"); Logger.LogInfo("Starting room cleanup thread...", LogArea.Startup);
RoomHelper.StartCleanupThread(); RoomHelper.StartCleanupThread();
stopwatch.Stop(); 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(); CreateHostBuilder(args).Build().Run();
} }
@ -91,7 +91,7 @@ public static class Program
database.Database.MigrateAsync().Wait(); database.Database.MigrateAsync().Wait();
stopwatch.Stop(); 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) public static IHostBuilder CreateHostBuilder(string[] args)

View file

@ -40,18 +40,18 @@ public class DebugWarmupLifetime : IHostLifetime
string url = ServerSettings.Instance.ServerListenUrl; string url = ServerSettings.Instance.ServerListenUrl;
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...", "Startup"); Logger.LogDebug("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.", "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(), "Startup"); Logger.LogDebug(e.ToDetailedException(), LogArea.Startup);
return; 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); public Task StopAsync(CancellationToken cancellationToken) => this.consoleLifetime.StopAsync(cancellationToken);

View file

@ -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. " + "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.",
"Startup" LogArea.Startup
); );
computeDigests = false; computeDigests = false;
} }
@ -144,7 +144,7 @@ public class Startup
Logger.LogInfo Logger.LogInfo
( (
$"{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}",
"HTTP" LogArea.HTTP
); );
#if DEBUG #if DEBUG
@ -152,7 +152,7 @@ public class Startup
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(), "HTTP"); Logger.LogDebug(await new StreamReader(context.Request.Body).ReadToEndAsync(), LogArea.HTTP);
} }
#endif #endif
} }

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", "Category"); Logger.LogError("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", "Category"); Logger.LogError("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", "Category"); Logger.LogError("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", "Category"); Logger.LogError("tried to serialize without user on CategoryWithUser", LogArea.Category);
return string.Empty; return string.Empty;
} }

View file

@ -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 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)) if (File.Exists(ConfigFileName))
{ {
@ -29,7 +29,7 @@ public class ServerSettings
if (Instance.ConfigVersion < CurrentConfigVersion) 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; Instance.ConfigVersion = CurrentConfigVersion;
configFile = JsonSerializer.Serialize configFile = JsonSerializer.Serialize
( (
@ -63,7 +63,7 @@ public class ServerSettings
"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 " +
$"{Path.Combine(Environment.CurrentDirectory, ConfigFileName)}", $"{Path.Combine(Environment.CurrentDirectory, ConfigFileName)}",
"Config" LogArea.Config
); );
Environment.Exit(1); Environment.Exit(1);
@ -72,7 +72,7 @@ public class ServerSettings
// Set up reloading // Set up reloading
if (Instance.ConfigReloading) if (Instance.ConfigReloading)
{ {
Logger.LogInfo("Setting up config reloading...", "Config"); Logger.LogInfo("Setting up config reloading...", LogArea.Config);
fileWatcher = new FileSystemWatcher fileWatcher = new FileSystemWatcher
{ {
Path = Environment.CurrentDirectory, Path = Environment.CurrentDirectory,
@ -89,8 +89,8 @@ public class ServerSettings
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.", "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.", "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); string configFile = File.ReadAllText(ConfigFileName);
Instance = JsonSerializer.Deserialize<ServerSettings>(configFile) ?? throw new ArgumentNullException(nameof(ConfigFileName)); Instance = JsonSerializer.Deserialize<ServerSettings>(configFile) ?? throw new ArgumentNullException(nameof(ConfigFileName));

View file

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

View file

@ -93,7 +93,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}", "Login"); Logger.LogDebug($"bodyHeader.Type is {bodyHeader.Type}", LogArea.Login);
switch (npTicket.ticketVersion) 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 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}", "Login"); Logger.LogDebug($"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}", "Login"); Logger.LogWarn($"Could not determine game version from title id {npTicket.titleId}", LogArea.Login);
return null; return null;
} }
@ -138,34 +138,35 @@ public class NPTicket
if (npTicket.Platform == Platform.Unknown) 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; return null;
} }
#if DEBUG #if DEBUG
Logger.LogDebug("npTicket data:", "Login"); Logger.LogDebug("npTicket data:", LogArea.Login);
Logger.LogDebug(JsonSerializer.Serialize(npTicket), "Login"); Logger.LogDebug(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.", "Login"); Logger.LogError($"The ticket version {npTicket.ticketVersion} is not implemented yet.", LogArea.Login);
Logger.LogError 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 !", "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; return null;
} }
catch(Exception e) catch(Exception e)
{ {
Logger.LogError("Failed to read npTicket!", "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.", "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!", "Login"); Logger.LogError
Logger.LogError(e.ToDetailedException(), "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);
return null; return null;
} }
} }