Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Add improved logging for SmtpService (#113)

Leendert de Borstd5cf51b5dac2
diff --git a/aliasvault.sln b/aliasvault.sln
index 7ba3b7df5..45f281355 100644
--- a/aliasvault.sln
+++ b/aliasvault.sln
@@ -45,6 +45,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.Admin", "src\Ali
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InitializationCLI", "src\Utilities\InitializationCLI\InitializationCLI.csproj", "{857BCD0E-753F-437A-AF75-B995B4D9A5FE}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AliasVault.Logging", "src\Utilities\AliasVault.Logging\AliasVault.Logging.csproj", "{FF0B0E64-1AE2-415C-A404-0EB78010821A}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -115,6 +117,10 @@ Global
{857BCD0E-753F-437A-AF75-B995B4D9A5FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{857BCD0E-753F-437A-AF75-B995B4D9A5FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{857BCD0E-753F-437A-AF75-B995B4D9A5FE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FF0B0E64-1AE2-415C-A404-0EB78010821A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FF0B0E64-1AE2-415C-A404-0EB78010821A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FF0B0E64-1AE2-415C-A404-0EB78010821A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FF0B0E64-1AE2-415C-A404-0EB78010821A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -132,6 +138,7 @@ Global
{B095A174-E528-4D38-BEC1-D1D38B3B30C0} = {8A477241-B96C-4174-968D-D40CB77F1ECD}
{1C7C8DE9-5F2A-43DB-A25E-33319E80A509} = {29DE523D-EEF2-41E9-AC12-F20D8D02BEBB}
{857BCD0E-753F-437A-AF75-B995B4D9A5FE} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}
+ {FF0B0E64-1AE2-415C-A404-0EB78010821A} = {01AB9389-2F89-4F8E-A688-BF4BF1FC42C8}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FEE82475-C009-4762-8113-A6563D9DC49E}
diff --git a/src/AliasVault.Admin/Program.cs b/src/AliasVault.Admin/Program.cs
index 6e23bb700..0a0b87a4e 100644
--- a/src/AliasVault.Admin/Program.cs
+++ b/src/AliasVault.Admin/Program.cs
@@ -18,6 +18,8 @@ using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
+builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
+builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
// Create global config object, get values from environment variables.
Config config = new Config();
@@ -58,12 +60,7 @@ builder.Services.ConfigureApplicationCookie(options =>
// as otherwise concurrency issues may occur if we use a single instance of the DbContext across the application.
builder.Services.AddSingleton<DbConnection>(container =>
{
- var configFile = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .Build();
-
- var connection = new SqliteConnection(configFile.GetConnectionString("AliasServerDbContext"));
+ var connection = new SqliteConnection(builder.Configuration.GetConnectionString("AliasServerDbContext"));
connection.Open();
return connection;
@@ -106,7 +103,6 @@ else
}
app.UseHttpsRedirection();
-
app.UseStaticFiles();
app.UseAntiforgery();
diff --git a/src/AliasVault.Api/Program.cs b/src/AliasVault.Api/Program.cs
index 966d46ac0..dda7f78ae 100644
--- a/src/AliasVault.Api/Program.cs
+++ b/src/AliasVault.Api/Program.cs
@@ -19,7 +19,8 @@ using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
-var configuration = builder.Configuration;
+builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
+builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
builder.Services.AddSingleton<ITimeProvider, SystemTimeProvider>();
builder.Services.AddScoped<TimeValidationJwtBearerEvents>();
@@ -34,12 +35,7 @@ builder.Services.AddLogging(logging =>
builder.Services.AddSingleton<DbConnection>(container =>
{
- var configFile = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .Build();
-
- var connection = new SqliteConnection(configFile.GetConnectionString("AliasServerDbContext"));
+ var connection = new SqliteConnection(builder.Configuration.GetConnectionString("AliasServerDbContext"));
connection.Open();
return connection;
@@ -92,8 +88,8 @@ builder.Services.AddAuthentication(options =>
ValidateLifetime = true,
RequireExpirationTime = true,
ValidateIssuerSigningKey = true,
- ValidIssuer = configuration["Jwt:Issuer"],
- ValidAudience = configuration["Jwt:Issuer"],
+ ValidIssuer = builder.Configuration["Jwt:Issuer"],
+ ValidAudience = builder.Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
ClockSkew = TimeSpan.Zero,
};
diff --git a/src/AliasVault.Client/Program.cs b/src/AliasVault.Client/Program.cs
index 50916c66b..903c614ec 100644
--- a/src/AliasVault.Client/Program.cs
+++ b/src/AliasVault.Client/Program.cs
@@ -13,20 +13,24 @@ using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
+builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
+builder.Configuration.AddJsonFile($"appsettings.{builder.HostEnvironment.Environment}.json", optional: true, reloadOnChange: true);
builder.Services.AddLogging(logging =>
{
- logging.SetMinimumLevel(LogLevel.Warning);
+ if (builder.HostEnvironment.IsDevelopment())
+ {
+ logging.SetMinimumLevel(LogLevel.Debug);
+ }
+ else
+ {
+ logging.SetMinimumLevel(LogLevel.Warning);
+ }
+
logging.AddFilter("Microsoft.AspNetCore.Identity.DataProtectorTokenProvider", LogLevel.Error);
logging.AddFilter("Microsoft.AspNetCore.Identity.UserManager", LogLevel.Error);
});
-builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
-if (builder.HostEnvironment.IsDevelopment())
-{
- builder.Configuration.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true);
-}
-
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddHttpClient("AliasVault.Api").AddHttpMessageHandler<AliasVaultApiHandlerService>();
diff --git a/src/Databases/AliasClientDb/AliasClientDbContext.cs b/src/Databases/AliasClientDb/AliasClientDbContext.cs
index 519f71d4f..6a5b33d44 100644
--- a/src/Databases/AliasClientDb/AliasClientDbContext.cs
+++ b/src/Databases/AliasClientDb/AliasClientDbContext.cs
@@ -135,7 +135,8 @@ public class AliasClientDbContext : DbContext
.UseSqlite(configuration.GetConnectionString("AliasClientDbContext"))
.UseLazyLoadingProxies();
- optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);
+ // Log queries made as debug output.
+ optionsBuilder.LogTo(Console.WriteLine);
}
base.OnConfiguring(optionsBuilder);
diff --git a/src/Databases/AliasServerDb/AliasServerDbContext.cs b/src/Databases/AliasServerDb/AliasServerDbContext.cs
index b0d24b91f..040d174bd 100644
--- a/src/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/src/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -99,6 +99,11 @@ public class AliasServerDbContext : DbContext
/// </summary>
public DbSet<EmailAttachment> EmailAttachments { get; set; }
+ /// <summary>
+ /// Gets or sets the Logs DbSet.
+ /// </summary>
+ public DbSet<Log> Logs { get; set; }
+
/// <summary>
/// The OnModelCreating method.
/// </summary>
@@ -151,6 +156,24 @@ public class AliasServerDbContext : DbContext
entity.HasKey(t => new { t.UserId, t.LoginProvider, t.Name });
entity.ToTable("UserTokens");
});
+
+ // Configure Log entity
+ modelBuilder.Entity<Log>(builder =>
+ {
+ builder.ToTable("Logs");
+ builder.Property(e => e.Application).HasMaxLength(50).IsRequired();
+ builder.Property(e => e.Message);
+ builder.Property(e => e.MessageTemplate);
+ builder.Property(e => e.Level).HasMaxLength(128);
+ builder.Property(e => e.TimeStamp);
+ builder.Property(e => e.Exception);
+ builder.Property(e => e.Properties);
+ builder.Property(e => e.LogEvent);
+
+ // Indexes for faster querying
+ builder.HasIndex(e => e.TimeStamp);
+ builder.HasIndex(e => e.Application);
+ });
}
/// <summary>
diff --git a/src/Databases/AliasServerDb/Log.cs b/src/Databases/AliasServerDb/Log.cs
new file mode 100644
index 000000000..af40a2faa
--- /dev/null
+++ b/src/Databases/AliasServerDb/Log.cs
@@ -0,0 +1,68 @@
+//-----------------------------------------------------------------------
+// <copyright file="Log.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasServerDb;
+
+using System;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+/// <summary>
+/// Represents a log entry in the AliasServerDb.
+/// </summary>
+public class Log
+{
+ /// <summary>
+ /// Gets or sets the unique identifier of the log entry.
+ /// </summary>
+ [Key]
+ public int Id { get; set; }
+
+ /// <summary>
+ /// Gets or sets the application name associated with the log entry.
+ /// </summary>
+ [Required]
+ [Column(TypeName = "nvarchar(50)")]
+ public string Application { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the log message.
+ /// </summary>
+ public string Message { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the message template for the log entry.
+ /// </summary>
+ public string MessageTemplate { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the log level.
+ /// </summary>
+ [Column(TypeName = "nvarchar(128)")]
+ public string Level { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the timestamp of the log entry.
+ /// </summary>
+ public DateTimeOffset TimeStamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the exception associated with the log entry.
+ /// </summary>
+ public string Exception { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the additional properties of the log entry.
+ /// </summary>
+ public string Properties { get; set; } = null!;
+
+ /// <summary>
+ /// Gets or sets the log event.
+ /// </summary>
+ [Column("LogEvent")]
+ public string LogEvent { get; set; } = null!;
+}
diff --git a/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.Designer.cs b/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.Designer.cs
new file mode 100644
index 000000000..97b3cf9e8
--- /dev/null
+++ b/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.Designer.cs
@@ -0,0 +1,536 @@
+// <auto-generated />
+using System;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ [DbContext(typeof(AliasServerDbContext))]
+ [Migration("20240723194939_CreateLogTable")]
+ partial class CreateLogTable
+ {
+ /// <inheritdoc />
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "8.0.6")
+ .HasAnnotation("Proxies:ChangeTracking", false)
+ .HasAnnotation("Proxies:CheckEquality", false)
+ .HasAnnotation("Proxies:LazyLoading", true);
+
+ modelBuilder.Entity("AliasServerDb.AdminRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminRoles");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AdminUser", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime?>("LastPasswordChanged")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AdminUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultRoles");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Property<string>("Id")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ConcurrencyStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Email")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<bool>("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTimeOffset?>("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedEmail")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("NormalizedUserName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Salt")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("UserName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Verifier")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("AliasVaultUsers");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("DeviceIdentifier")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("ExpireDate")
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("AliasVaultUserRefreshTokens");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("DateSystem")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("From")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("FromDomain")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("FromLocal")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessageHtml")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessagePlain")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessagePreview")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessageSource")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("PushNotificationSent")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Subject")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("To")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ToDomain")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ToLocal")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<bool>("Visible")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Date");
+
+ b.HasIndex("DateSystem");
+
+ b.HasIndex("PushNotificationSent");
+
+ b.HasIndex("ToLocal");
+
+ b.HasIndex("Visible");
+
+ b.ToTable("Emails");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("Bytes")
+ .IsRequired()
+ .HasColumnType("BLOB");
+
+ b.Property<DateTime>("Date")
+ .HasColumnType("TEXT");
+
+ b.Property<int>("EmailId")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Filename")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<int>("Filesize")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("MimeType")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EmailId");
+
+ b.ToTable("EmailAttachments");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Log", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Application")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Exception")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Level")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("LogEvent")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasColumnName("LogEvent");
+
+ b.Property<string>("Message")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessageTemplate")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Properties")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTimeOffset>("TimeStamp")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Application");
+
+ b.HasIndex("TimeStamp");
+
+ b.ToTable("Logs", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("VaultBlob")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Version")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("Vaults");
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("RoleClaims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("ClaimType")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ClaimValue")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.ToTable("UserClaims", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
+ {
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderKey")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("ProviderDisplayName")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("LoginProvider", "ProviderKey");
+
+ b.ToTable("UserLogins", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
+ {
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("RoleId")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "RoleId");
+
+ b.ToTable("UserRoles", (string)null);
+ });
+
+ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
+ {
+ b.Property<string>("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("LoginProvider")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Value")
+ .HasColumnType("TEXT");
+
+ b.HasKey("UserId", "LoginProvider", "Name");
+
+ b.ToTable("UserTokens", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Attachments")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Vault", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Navigation("Attachments");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.cs b/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.cs
new file mode 100644
index 000000000..f69eefdf2
--- /dev/null
+++ b/src/Databases/AliasServerDb/Migrations/20240723194939_CreateLogTable.cs
@@ -0,0 +1,52 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class CreateLogTable : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "Logs",
+ columns: table => new
+ {
+ Id = table.Column<int>(type: "INTEGER", nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ Application = table.Column<string>(type: "TEXT", maxLength: 50, nullable: false),
+ Message = table.Column<string>(type: "TEXT", nullable: false),
+ MessageTemplate = table.Column<string>(type: "TEXT", nullable: false),
+ Level = table.Column<string>(type: "TEXT", maxLength: 128, nullable: false),
+ TimeStamp = table.Column<DateTimeOffset>(type: "TEXT", nullable: false),
+ Exception = table.Column<string>(type: "TEXT", nullable: false),
+ Properties = table.Column<string>(type: "TEXT", nullable: false),
+ LogEvent = table.Column<string>(type: "TEXT", nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_Logs", x => x.Id);
+ });
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Logs_Application",
+ table: "Logs",
+ column: "Application");
+
+ migrationBuilder.CreateIndex(
+ name: "IX_Logs_TimeStamp",
+ table: "Logs",
+ column: "TimeStamp");
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "Logs");
+ }
+ }
+}
diff --git a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index ccbac66e9..5717731c1 100644
--- a/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/src/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -317,6 +317,55 @@ namespace AliasServerDb.Migrations
b.ToTable("EmailAttachments");
});
+ modelBuilder.Entity("AliasServerDb.Log", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Application")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Exception")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Level")
+ .IsRequired()
+ .HasMaxLength(128)
+ .HasColumnType("TEXT");
+
+ b.Property<string>("LogEvent")
+ .IsRequired()
+ .HasColumnType("TEXT")
+ .HasColumnName("LogEvent");
+
+ b.Property<string>("Message")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("MessageTemplate")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Properties")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property<DateTimeOffset>("TimeStamp")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Application");
+
+ b.HasIndex("TimeStamp");
+
+ b.ToTable("Logs", (string)null);
+ });
+
modelBuilder.Entity("AliasServerDb.Vault", b =>
{
b.Property<Guid>("Id")
diff --git a/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj b/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
index cf16cdd4e..1cb996886 100644
--- a/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
+++ b/src/Services/AliasVault.SmtpService/AliasVault.SmtpService.csproj
@@ -23,5 +23,10 @@
<ItemGroup>
<ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ <ProjectReference Include="..\..\Utilities\AliasVault.Logging\AliasVault.Logging.csproj" />
+ </ItemGroup>
+
+ <ItemGroup>
+ <Folder Include="logs\" />
</ItemGroup>
</Project>
diff --git a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 3839cb375..e8f1b1f39 100644
--- a/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/src/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -71,7 +71,7 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
if (toAddress == null)
{
// No toAddress, skip.
- logger.LogWarning("Skip email, no toAddress available");
+ logger.LogWarning("Skip email, no toAddress available.");
return SmtpResponse.NoValidRecipientsGiven;
}
if (!config.AllowedToDomains.Contains(toAddress.Host.ToLowerInvariant()))
@@ -84,12 +84,12 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
}
// If only one recipient, return error.
- logger.LogWarning("Email to {ToAddress} is not allowed", toAddress.User + "@" + toAddress.Host);
+ logger.LogWarning("Rejected email: email for {ToAddress} is not allowed.", toAddress.User + "@" + toAddress.Host);
return SmtpResponse.NoValidRecipientsGiven;
}
var insertedId = await InsertEmailIntoDatabase(message);
- logger.LogInformation("Email saved into database with ID {insertedId}.", insertedId);
+ logger.LogInformation("Email for {ToAddress} successfully saved into database with ID {insertedId}.", toAddress.User + "@" + toAddress.Host, insertedId);
}
return SmtpResponse.Ok;
diff --git a/src/Services/AliasVault.SmtpService/Program.cs b/src/Services/AliasVault.SmtpService/Program.cs
index 4aea2c4ab..024dff907 100644
--- a/src/Services/AliasVault.SmtpService/Program.cs
+++ b/src/Services/AliasVault.SmtpService/Program.cs
@@ -14,8 +14,12 @@ using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using SmtpServer;
using SmtpServer.Storage;
+using AliasVault.Logging;
var builder = Host.CreateApplicationBuilder(args);
+builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
+builder.Configuration.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+builder.Services.ConfigureLogging(builder.Configuration, "SmtpService");
// Create global config object, get values from environment variables.
Config config = new Config();
@@ -30,12 +34,7 @@ builder.Services.AddSingleton(config);
builder.Services.AddSingleton<DbConnection>(container =>
{
- var configFile = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json")
- .Build();
-
- var connection = new SqliteConnection(configFile.GetConnectionString("AliasServerDbContext"));
+ var connection = new SqliteConnection(builder.Configuration.GetConnectionString("AliasServerDbContext"));
connection.Open();
return connection;
@@ -125,9 +124,9 @@ var host = builder.Build();
using (var scope = host.Services.CreateScope())
{
var container = scope.ServiceProvider;
- var db = container.GetRequiredService<AliasServerDbContext>();
-
- await db.Database.MigrateAsync();
+ var factory = container.GetRequiredService<IDbContextFactory<AliasServerDbContext>>();
+ await using var context = await factory.CreateDbContextAsync();
+ await context.Database.MigrateAsync();
}
await host.RunAsync();
diff --git a/src/Services/AliasVault.SmtpService/Worker.cs b/src/Services/AliasVault.SmtpService/Worker.cs
index 028d9707a..3ca9c97fc 100644
--- a/src/Services/AliasVault.SmtpService/Worker.cs
+++ b/src/Services/AliasVault.SmtpService/Worker.cs
@@ -5,18 +5,44 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace AliasVault.SmtpService
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+
+namespace AliasVault.SmtpService;
+
+public class Worker(ILogger<Worker> logger, SmtpServer.SmtpServer smtpServer, IDbContextFactory<AliasServerDbContext> contextFactory) : BackgroundService
{
- public class Worker(ILogger<Worker> logger, SmtpServer.SmtpServer smtpServer) : BackgroundService
+ /// <inheritdoc />
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
- /// <inheritdoc />
- protected override Task ExecuteAsync(CancellationToken stoppingToken)
+ try
+ {
+ logger.LogWarning("AliasVault.SmtpService starting at: {Time}", DateTimeOffset.Now);
+
+ // Start the SMTP server
+ await smtpServer.StartAsync(stoppingToken);
+
+ // Wait for the cancellation token to be triggered
+ await Task.Delay(Timeout.Infinite, stoppingToken);
+ }
+ catch (OperationCanceledException)
{
- if (logger.IsEnabled(LogLevel.Information))
- {
- logger.LogInformation("AliasVault.SmtpService running at: {Time}", DateTimeOffset.Now);
- }
- return smtpServer.StartAsync(stoppingToken);
+ // This exception is thrown when the stoppingToken is canceled
+ // It's expected behavior, so we can just log it
+ logger.LogWarning("AliasVault.SmtpService is stopping due to a cancellation request");
+ }
+ catch (Exception ex)
+ {
+ // Log any unexpected exceptions
+ logger.LogError(ex, "An error occurred in AliasVault.SmtpService");
+ }
+ finally
+ {
+ // Log that the service is stopping, whether it's due to cancellation or an error
+ logger.LogWarning("AliasVault.SmtpService stopped at: {Time}", DateTimeOffset.Now);
+
+ // Ensure the SMTP server is stopped
+ smtpServer.Shutdown();
}
}
}
diff --git a/src/Services/AliasVault.SmtpService/appsettings.Development.json b/src/Services/AliasVault.SmtpService/appsettings.Development.json
index b2dcdb674..df591876d 100644
--- a/src/Services/AliasVault.SmtpService/appsettings.Development.json
+++ b/src/Services/AliasVault.SmtpService/appsettings.Development.json
@@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
- "Microsoft.Hosting.Lifetime": "Information"
+ "Microsoft.Hosting.Lifetime": "Information",
+ "Microsoft.EntityFrameworkCore": "Warning"
}
}
}
diff --git a/src/Services/AliasVault.SmtpService/appsettings.json b/src/Services/AliasVault.SmtpService/appsettings.json
index c74fb8b2a..ddbf1678f 100644
--- a/src/Services/AliasVault.SmtpService/appsettings.json
+++ b/src/Services/AliasVault.SmtpService/appsettings.json
@@ -1,8 +1,9 @@
{
"Logging": {
"LogLevel": {
- "Default": "Information",
- "Microsoft.Hosting.Lifetime": "Information"
+ "Default": "Warning",
+ "Microsoft.Hosting.Lifetime": "Information",
+ "Microsoft.EntityFrameworkCore": "Warning"
}
},
"ConnectionStrings": {
diff --git a/src/Utilities/AliasVault.Logging/AliasVault.Logging.csproj b/src/Utilities/AliasVault.Logging/AliasVault.Logging.csproj
new file mode 100644
index 000000000..fa7cd792d
--- /dev/null
+++ b/src/Utilities/AliasVault.Logging/AliasVault.Logging.csproj
@@ -0,0 +1,47 @@
+<Project Sdk="Microsoft.NET.Sdk">
+
+ <PropertyGroup>
+ <TargetFramework>net8.0</TargetFramework>
+ <ImplicitUsings>enable</ImplicitUsings>
+ <Nullable>enable</Nullable>
+ <RootNamespace>Logging</RootNamespace>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
+ <DocumentationFile>bin\Debug\net8.0\AliasVault.Logging.xml</DocumentationFile>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
+ <DocumentationFile>bin\Release\net8.0\AliasVault.Logging.xml</DocumentationFile>
+ <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+ </PropertyGroup>
+
+ <ItemGroup>
+ <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
+ <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
+ <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
+ <PackageReference Include="Serilog" Version="4.0.0" />
+ <PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
+ <PackageReference Include="Serilog.Settings.Configuration" Version="8.0.2" />
+ <PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
+ <PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
+ <PackageReference Include="Serilog.Sinks.SQLite" Version="6.0.0" />
+ <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
+ <PrivateAssets>all</PrivateAssets>
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ </PackageReference>
+ </ItemGroup>
+
+ <ItemGroup>
+ <AdditionalFiles Include="..\..\stylecop.json">
+ <Link>stylecop.json</Link>
+ </AdditionalFiles>
+ </ItemGroup>
+
+ <ItemGroup>
+ <ProjectReference Include="..\..\Databases\AliasServerDb\AliasServerDb.csproj" />
+ </ItemGroup>
+
+</Project>
diff --git a/src/Utilities/AliasVault.Logging/DatabaseSink.cs b/src/Utilities/AliasVault.Logging/DatabaseSink.cs
new file mode 100644
index 000000000..9a100016f
--- /dev/null
+++ b/src/Utilities/AliasVault.Logging/DatabaseSink.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="DatabaseSink.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Logging;
+
+using System;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+using Serilog.Core;
+using Serilog.Events;
+
+/// <summary>
+/// Custom Serilog sink for Database via Entity Framework Core.
+/// </summary>
+/// <param name="formatProvider">IFormatProvider instance.</param>
+/// <param name="contextFactory">DB context factory to use.</param>
+/// <param name="applicationName">Application name.</param>
+public class DatabaseSink(IFormatProvider formatProvider, Func<IDbContextFactory<AliasServerDbContext>> contextFactory, string applicationName) : ILogEventSink
+{
+ /// <summary>
+ /// Saves the log event to the database.
+ /// </summary>
+ /// <param name="logEvent">LogEvent instance.</param>
+ public void Emit(LogEvent logEvent)
+ {
+ var logEntry = new Log
+ {
+ TimeStamp = logEvent.Timestamp.UtcDateTime,
+ Level = logEvent.Level.ToString(),
+ Message = logEvent.RenderMessage(formatProvider),
+ Exception = logEvent.Exception?.ToString() ?? string.Empty,
+ Properties = logEvent.Properties.ToString() ?? string.Empty,
+ LogEvent = string.Empty,
+ MessageTemplate = string.Empty,
+ Application = applicationName,
+ };
+
+ try
+ {
+ using var context = contextFactory.Invoke().CreateDbContext();
+ context.Logs.Add(logEntry);
+ context.SaveChanges();
+ }
+ catch (Exception ex)
+ {
+ Console.WriteLine($"Error writing log entry to database: {ex}");
+ }
+ }
+}
diff --git a/src/Utilities/AliasVault.Logging/LoggingConfiguration.cs b/src/Utilities/AliasVault.Logging/LoggingConfiguration.cs
new file mode 100644
index 000000000..acce42f24
--- /dev/null
+++ b/src/Utilities/AliasVault.Logging/LoggingConfiguration.cs
@@ -0,0 +1,103 @@
+//-----------------------------------------------------------------------
+// <copyright file="LoggingConfiguration.cs" company="lanedirt">
+// Copyright (c) lanedirt. All rights reserved.
+// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Logging;
+
+using System.Globalization;
+using AliasServerDb;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Serilog;
+using Serilog.Events;
+using Serilog.Filters;
+
+/// <summary>
+/// Extension methods for configuring logging.
+/// </summary>
+public static class LoggingConfiguration
+{
+ /// <summary>
+ /// Configures Serilog logging for the application.
+ /// </summary>
+ /// <param name="services">IServiceCollection.</param>
+ /// <param name="configuration">IConfiguration.</param>
+ /// <param name="applicationName">The application name to include in the log.</param>
+ /// <returns>IServiceCollection instance.</returns>
+ public static IServiceCollection ConfigureLogging(this IServiceCollection services, IConfiguration configuration, string applicationName)
+ {
+ services.AddSerilog(new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .Enrich.FromLogContext()
+ .Enrich.WithProperty("Application", applicationName)
+ .Filter.ByIncludingOnly(GetSourceContextFilter(configuration))
+
+ // Log to console.
+ .WriteTo.Logger(lc => lc
+ .WriteTo.Console())
+
+ // Log everything to a file.
+ .WriteTo.Logger(lc => lc
+ .WriteTo.File($"logs/{applicationName}-log-.txt", rollingInterval: RollingInterval.Day))
+
+ // Log all errors and above to a separate file.
+ .WriteTo.Logger(lc => lc
+ .Filter.ByIncludingOnly(evt => evt.Level >= LogEventLevel.Error)
+ .WriteTo.File($"logs/{applicationName}-error-.txt", rollingInterval: RollingInterval.Day))
+
+ // Log all warning and above to database via EF core except for Microsoft.EntityFrameworkCore logs
+ // as this would create a loop.
+ .WriteTo.Logger(lc => lc
+ .Filter.ByIncludingOnly(evt => evt.Level >= LogEventLevel.Warning)
+ .Filter.ByExcluding(Matching.FromSource("Microsoft.EntityFrameworkCore"))
+ .WriteTo.Sink(new DatabaseSink(CultureInfo.InvariantCulture, () => services.BuildServiceProvider().GetRequiredService<IDbContextFactory<AliasServerDbContext>>(), applicationName)))
+ .CreateLogger());
+
+ return services;
+ }
+
+ /// <summary>
+ /// Helper method to create the source context filter.
+ /// </summary>
+ /// <param name="configuration">IConfiguration instance.</param>
+ /// <returns>Source context filter for serilog builder.</returns>
+ private static Func<LogEvent, bool> GetSourceContextFilter(IConfiguration configuration)
+ {
+ return evt =>
+ {
+ var sourceContext = evt.Properties.ContainsKey("SourceContext")
+ ? evt.Properties["SourceContext"].ToString()
+ : string.Empty;
+ var configuredLevel = GetLogEventLevel(sourceContext, configuration);
+ return evt.Level >= configuredLevel;
+ };
+ }
+
+ /// <summary>
+ /// Gets the log event level for the source context based on IConfiguration (appsettings.json).
+ /// </summary>
+ /// <param name="sourceContext">The source context to look for in the configuration.</param>
+ /// <param name="configuration">IConfiguration instance.</param>
+ /// <returns>LogEventLevel enum.</returns>
+ private static LogEventLevel GetLogEventLevel(string sourceContext, IConfiguration configuration)
+ {
+ var logLevels = configuration.GetSection("Logging:LogLevel");
+
+ // Check if this specific source context has an override level defined in appsettings.json.
+ foreach (var logLevel in logLevels.GetChildren())
+ {
+ if (sourceContext.Contains(logLevel.Key, StringComparison.OrdinalIgnoreCase))
+ {
+ return Enum.Parse<LogEventLevel>(logLevel.Value ?? "Information", true);
+ }
+ }
+
+ // If no specific override, use the default.
+ var defaultLevel = logLevels["Default"] ?? "Information";
+ return Enum.Parse<LogEventLevel>(defaultLevel, true);
+ }
+}