From a407a231012dffff2b266aed3c0bbb3861b8e686 Mon Sep 17 00:00:00 2001 From: Leendert de Borst Date: Tue, 24 Sep 2024 22:52:24 +0200 Subject: [PATCH] Implement ILogger for all client side console logging calls (#233) --- .gitignore | 4 ++++ .../Auth/Pages/Register.razor | 4 +++- .../Main/Components/Email/RecentEmails.razor | 3 ++- .../Components/Widgets/SearchWidget.razor | 1 - .../Main/Pages/Emails/Home.razor | 3 ++- .../Main/Pages/Settings/Vault.razor | 7 +++--- .../Main/Pages/Sync/Sync.razor | 2 +- src/AliasVault.Client/Program.cs | 2 +- .../Providers/AuthStateProvider.cs | 6 ++--- .../Auth/AliasVaultApiHandlerService.cs | 3 ++- .../Services/Database/DbMergeUtility.cs | 22 +++++++++---------- .../Services/Database/DbService.cs | 6 ++--- .../Services/EmailService.cs | 6 ++--- .../AliasClientDb/AliasClientDbContext.cs | 2 +- 14 files changed, 39 insertions(+), 32 deletions(-) diff --git a/.gitignore b/.gitignore index c4730a9e7..fd788b467 100644 --- a/.gitignore +++ b/.gitignore @@ -371,6 +371,9 @@ FodyWeavers.xsd .idea *.licenseheader +# Codebuddy Rider plugin +.codebuddy + # AliasVault specific # index.html is generated by the build process from index.template.html and therefore should be ignored src/AliasVault.Client/wwwroot/index.html @@ -381,3 +384,4 @@ src/Tests/AliasVault.E2ETests/appsettings.Development.json # .env is generated by install.sh and therefore should be ignored .env + diff --git a/src/AliasVault.Client/Auth/Pages/Register.razor b/src/AliasVault.Client/Auth/Pages/Register.razor index 2198b376c..2deda13b0 100644 --- a/src/AliasVault.Client/Auth/Pages/Register.razor +++ b/src/AliasVault.Client/Auth/Pages/Register.razor @@ -112,7 +112,9 @@ else { // Handle the case where the token is not present in the response - Console.WriteLine("Token not found in the response."); + ServerValidationErrors.AddError("An error occured during registration."); + StateHasChanged(); + return; } NavigationManager.NavigateTo("/"); diff --git a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor index da56d8ee1..b6fb427a4 100644 --- a/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor +++ b/src/AliasVault.Client/Main/Components/Email/RecentEmails.razor @@ -10,6 +10,7 @@ @inject Config Config @inject EmailService EmailService @using System.Timers +@inject ILogger Logger @implements IDisposable @if (EmailModalVisible) @@ -327,7 +328,7 @@ catch (Exception ex) { Error = ex.Message; - Console.WriteLine(ex); + Logger.LogError(ex, "An error occurred while loading AliasVault emails."); } } diff --git a/src/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor b/src/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor index 0778352f1..f91835954 100644 --- a/src/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor +++ b/src/AliasVault.Client/Main/Components/Widgets/SearchWidget.razor @@ -100,7 +100,6 @@ private async Task SearchTermChanged(ChangeEventArgs e) { - Console.WriteLine("Search term changed"); SearchTerm = e.Value?.ToString() ?? string.Empty; await PerformSearch(); } diff --git a/src/AliasVault.Client/Main/Pages/Emails/Home.razor b/src/AliasVault.Client/Main/Pages/Emails/Home.razor index 4bbfb0b98..453d6c789 100644 --- a/src/AliasVault.Client/Main/Pages/Emails/Home.razor +++ b/src/AliasVault.Client/Main/Pages/Emails/Home.razor @@ -8,6 +8,7 @@ @using AliasVault.Shared.Models.WebApi.Email @inherits MainBase @inject HttpClient HttpClient +@inject ILogger Logger Emails @@ -181,7 +182,7 @@ else catch (Exception ex) { GlobalNotificationService.AddErrorMessage(ex.Message, true); - Console.WriteLine(ex); + Logger.LogError(ex, "An error occurred while refreshing data"); } IsLoading = false; diff --git a/src/AliasVault.Client/Main/Pages/Settings/Vault.razor b/src/AliasVault.Client/Main/Pages/Settings/Vault.razor index 8a330df26..550a687eb 100644 --- a/src/AliasVault.Client/Main/Pages/Settings/Vault.razor +++ b/src/AliasVault.Client/Main/Pages/Settings/Vault.razor @@ -1,6 +1,7 @@ @page "/settings/vault" @inherits MainBase @inject CredentialService CredentialService +@inject ILogger Logger Vault settings @@ -54,7 +55,7 @@ else if (!string.IsNullOrEmpty(ImportSuccessMessage)) } @code { - private bool IsImporting = false; + private bool IsImporting; private string ImportErrorMessage = string.Empty; private string ImportSuccessMessage = string.Empty; @@ -81,7 +82,7 @@ else if (!string.IsNullOrEmpty(ImportSuccessMessage)) } catch (Exception ex) { - Console.WriteLine($"Error downloading file: {ex.Message}"); + Logger.LogError(ex, "Error downloading file"); } } @@ -102,7 +103,7 @@ else if (!string.IsNullOrEmpty(ImportSuccessMessage)) } catch (Exception ex) { - Console.WriteLine($"Error downloading file: {ex.Message}"); + Logger.LogError(ex, "Error downloading file"); } } diff --git a/src/AliasVault.Client/Main/Pages/Sync/Sync.razor b/src/AliasVault.Client/Main/Pages/Sync/Sync.razor index 20336f172..c62b2c06e 100644 --- a/src/AliasVault.Client/Main/Pages/Sync/Sync.razor +++ b/src/AliasVault.Client/Main/Pages/Sync/Sync.razor @@ -91,7 +91,7 @@ await RedirectBackToReturnUrl(); } - Logger.LogDebug("Database state changed: " + CurrentDbState.Status); + Logger.LogDebug("Database state changed: {NewStatus}", CurrentDbState.Status); StateHasChanged(); } diff --git a/src/AliasVault.Client/Program.cs b/src/AliasVault.Client/Program.cs index 222a3ec27..544bf827c 100644 --- a/src/AliasVault.Client/Program.cs +++ b/src/AliasVault.Client/Program.cs @@ -35,7 +35,7 @@ builder.Services.AddLogging(logging => { if (builder.HostEnvironment.IsDevelopment()) { - logging.SetMinimumLevel(LogLevel.Debug); + logging.SetMinimumLevel(LogLevel.Trace); } else { diff --git a/src/AliasVault.Client/Providers/AuthStateProvider.cs b/src/AliasVault.Client/Providers/AuthStateProvider.cs index 93115923f..4745e5046 100644 --- a/src/AliasVault.Client/Providers/AuthStateProvider.cs +++ b/src/AliasVault.Client/Providers/AuthStateProvider.cs @@ -15,7 +15,7 @@ using Microsoft.AspNetCore.Components.Authorization; /// /// Custom authentication state provider for the application. /// -public class AuthStateProvider(AuthService authService) : AuthenticationStateProvider +public class AuthStateProvider(AuthService authService, ILogger logger) : AuthenticationStateProvider { /// /// Parses the claims from the JWT token. @@ -52,9 +52,9 @@ public class AuthStateProvider(AuthService authService) : AuthenticationStatePro { identity = new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt"); } - catch (Exception) + catch (Exception ex) { - Console.WriteLine("Invalid JWT token. Removing..."); + logger.LogError(ex, "Invalid JWT token. Removing..."); await authService.RemoveTokensAsync(); identity = new ClaimsIdentity(); } diff --git a/src/AliasVault.Client/Services/Auth/AliasVaultApiHandlerService.cs b/src/AliasVault.Client/Services/Auth/AliasVaultApiHandlerService.cs index a835d7f72..0a50fcc17 100644 --- a/src/AliasVault.Client/Services/Auth/AliasVaultApiHandlerService.cs +++ b/src/AliasVault.Client/Services/Auth/AliasVaultApiHandlerService.cs @@ -55,7 +55,8 @@ public sealed class AliasVaultApiHandlerService(IServiceProvider serviceProvider return response; } - Console.WriteLine("Failed to refresh token, redirect to login."); + var logger = serviceProvider.GetRequiredService>(); + logger.LogError("Failed to refresh token, redirect to login."); // Refreshing token failed. This might be caused by the expiration or revocation of the refresh token itself. // Remove the token from local storage and redirect to the login page. diff --git a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs b/src/AliasVault.Client/Services/Database/DbMergeUtility.cs index 990c93e0e..f9fab4401 100644 --- a/src/AliasVault.Client/Services/Database/DbMergeUtility.cs +++ b/src/AliasVault.Client/Services/Database/DbMergeUtility.cs @@ -41,8 +41,9 @@ public static class DbMergeUtility /// The connection to the base database. /// The connection to the source database. /// The name of the table to merge. + /// ILogger instance. /// Task. - public static async Task MergeTable(SqliteConnection baseConnection, SqliteConnection sourceConnection, string tableName) + public static async Task MergeTable(SqliteConnection baseConnection, SqliteConnection sourceConnection, string tableName, ILogger logger) { await using var baseCommand = baseConnection.CreateCommand(); await using var sourceCommand = sourceConnection.CreateCommand(); @@ -71,8 +72,7 @@ public static class DbMergeUtility sourceCommand.CommandText = $"SELECT * FROM {tableName}"; await using var sourceReader = await sourceCommand.ExecuteReaderAsync(); - Console.WriteLine($"Got records for {tableName}."); - + logger.LogDebug("Got records for {tableName}.", tableName); while (await sourceReader.ReadAsync()) { var id = sourceReader.GetValue(0); @@ -83,16 +83,16 @@ public static class DbMergeUtility baseCommand.Parameters.Clear(); baseCommand.Parameters.AddWithValue("@Id", id); - Console.WriteLine($"Checking if record exists in {tableName}."); + logger.LogDebug("Checking if record exists in {tableName}.", tableName); var existingRecord = await baseCommand.ExecuteScalarAsync(); if (existingRecord != null) { - Console.WriteLine($"Record exists in {tableName}."); + logger.LogDebug("Record exists in {tableName}.", tableName); // Record exists, compare UpdatedAt if it exists. - Console.WriteLine($"Comparing UpdatedAt in {tableName}."); - Console.WriteLine($"UpdatedAt: {existingRecord}"); + logger.LogDebug("Comparing UpdatedAt in {tableName}.", tableName); + logger.LogDebug("UpdatedAt: {existingRecord}", existingRecord); var baseUpdatedAt = DateTime.Parse((string)existingRecord, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal); if (updatedAt > baseUpdatedAt) { @@ -101,7 +101,8 @@ public static class DbMergeUtility } else { - Console.WriteLine($"Base record is newer, skipping {tableName}."); + // Base record is newer, skip. + logger.LogDebug("Base record is newer, skipping {tableName}.", tableName); } } else @@ -111,7 +112,7 @@ public static class DbMergeUtility } } - Console.WriteLine($"Merged {tableName}."); + logger.LogDebug("Finished merging {tableName}.", tableName); } /// @@ -151,9 +152,6 @@ public static class DbMergeUtility var updateColumns = string.Join(", ", columns.Select(c => $"{c} = @{c}")); command.CommandText = $"UPDATE {tableName} SET {updateColumns} WHERE Id = @Id"; - Console.WriteLine($"Updating record in {tableName}."); - Console.WriteLine($"Command: {command.CommandText}"); - for (int i = 0; i < columns.Count; i++) { command.Parameters.AddWithValue($"@{columns[i]}", sourceReader.GetValue(i)); diff --git a/src/AliasVault.Client/Services/Database/DbService.cs b/src/AliasVault.Client/Services/Database/DbService.cs index 863cea573..98af7df11 100644 --- a/src/AliasVault.Client/Services/Database/DbService.cs +++ b/src/AliasVault.Client/Services/Database/DbService.cs @@ -146,7 +146,7 @@ public sealed class DbService : IDisposable foreach (var table in tables) { _logger.LogInformation("Merging table {Table}.", table); - await DbMergeUtility.MergeTable(_sqlConnection, connection, table); + await DbMergeUtility.MergeTable(_sqlConnection, connection, table, _logger); } } @@ -168,7 +168,7 @@ public sealed class DbService : IDisposable } // Update the db context with the new merged database. - _dbContext = new AliasClientDbContext(_sqlConnection, log => _logger.LogInformation(log)); + _dbContext = new AliasClientDbContext(_sqlConnection, log => _logger.LogDebug("{Message}", log)); // Clean up other connections. foreach (var connection in sqlConnections) @@ -406,7 +406,7 @@ public sealed class DbService : IDisposable _sqlConnection = new SqliteConnection("Data Source=:memory:"); _sqlConnection.Open(); - _dbContext = new AliasClientDbContext(_sqlConnection, log => _logger.LogInformation(log)); + _dbContext = new AliasClientDbContext(_sqlConnection, log => _logger.LogDebug("{Message}", log)); // Reset the database state. _state.UpdateState(DbServiceState.DatabaseStatus.Uninitialized); diff --git a/src/AliasVault.Client/Services/EmailService.cs b/src/AliasVault.Client/Services/EmailService.cs index 246ef9a57..0d42c3ab0 100644 --- a/src/AliasVault.Client/Services/EmailService.cs +++ b/src/AliasVault.Client/Services/EmailService.cs @@ -14,7 +14,7 @@ using Microsoft.EntityFrameworkCore; /// /// Email service that contains utility methods for handling email functionality such as client-side decryption. /// -public sealed class EmailService(DbService dbService, JsInteropService jsInteropService, GlobalNotificationService globalNotificationService) +public sealed class EmailService(DbService dbService, JsInteropService jsInteropService, GlobalNotificationService globalNotificationService, ILogger logger) { private List _encryptionKeys = []; @@ -54,7 +54,7 @@ public sealed class EmailService(DbService dbService, JsInteropService jsInterop catch (Exception ex) { globalNotificationService.AddErrorMessage(ex.Message, true); - Console.WriteLine(ex); + logger.LogError(ex, "Error decrypting email list."); } } @@ -91,7 +91,7 @@ public sealed class EmailService(DbService dbService, JsInteropService jsInterop catch (Exception ex) { globalNotificationService.AddErrorMessage(ex.Message, true); - Console.WriteLine(ex); + logger.LogError(ex, "Error decrypting email."); } return email; diff --git a/src/Databases/AliasClientDb/AliasClientDbContext.cs b/src/Databases/AliasClientDb/AliasClientDbContext.cs index 5e7a0137e..e9fd71d0b 100644 --- a/src/Databases/AliasClientDb/AliasClientDbContext.cs +++ b/src/Databases/AliasClientDb/AliasClientDbContext.cs @@ -156,7 +156,7 @@ public class AliasClientDbContext : DbContext { var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseSqlite(connection); - optionsBuilder.LogTo(logAction, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Warning); + optionsBuilder.LogTo(logAction, new[] { DbLoggerCategory.Database.Command.Name }); return optionsBuilder.Options; }