From 0ecba36f51d5fc934d6aafeabc388215be080735 Mon Sep 17 00:00:00 2001 From: Lorenz Stechauner Date: Mon, 24 Apr 2023 13:51:01 +0200 Subject: [PATCH] Add database log file --- Elwig/Helpers/AppDbContext.cs | 30 ++++++++++++++++++++++++++++++ Elwig/Helpers/Config.cs | 12 +++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Elwig/Helpers/AppDbContext.cs b/Elwig/Helpers/AppDbContext.cs index 11a6113..0aa3824 100644 --- a/Elwig/Helpers/AppDbContext.cs +++ b/Elwig/Helpers/AppDbContext.cs @@ -2,6 +2,10 @@ using Microsoft.EntityFrameworkCore; using Elwig.Models; using System.Linq; using System.Threading.Tasks; +using System.IO; +using System; +using System.Windows; +using Microsoft.Extensions.Logging; namespace Elwig.Helpers { public class AppDbContext : DbContext { @@ -29,12 +33,38 @@ namespace Elwig.Helpers { public DbSet WineVarieties { get; set; } public DbSet Seasons { get; set; } + private readonly StreamWriter? LogFile = null; + + public AppDbContext() { + if (App.Config.DatabaseLog != null) { + try { + var file = File.Open(App.Config.DatabaseLog, FileMode.Append, FileAccess.Write, FileShare.Write); + LogFile = new(file) { + AutoFlush = true + }; + } catch (Exception e) { + MessageBox.Show($"Unable to open database log file:\n\n{e}", "Database Log", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite($"Data Source=\"{App.Config.DatabaseFile}\"; Foreign Keys=True; Mode=ReadWrite; Cache=Default"); optionsBuilder.UseLazyLoadingProxies(); + optionsBuilder.LogTo(Log, LogLevel.Information); base.OnConfiguring(optionsBuilder); } + public override void Dispose() { + base.Dispose(); + LogFile?.Dispose(); + GC.SuppressFinalize(this); + } + + protected void Log(string msg) { + LogFile?.WriteLine(msg); + } + public async Task MgNrExists(int mgnr) { return await Members.FindAsync(mgnr) != null; } diff --git a/Elwig/Helpers/Config.cs b/Elwig/Helpers/Config.cs index 3acf67d..3c4f411 100644 --- a/Elwig/Helpers/Config.cs +++ b/Elwig/Helpers/Config.cs @@ -8,6 +8,7 @@ namespace Elwig.Helpers { private readonly string FileName; public string DatabaseFile = App.DataPath + "database.sqlite3"; + public string? DatabaseLog = null; public Config(string filename) { FileName = filename; @@ -28,11 +29,20 @@ namespace Elwig.Helpers { } else { DatabaseFile = App.DataPath + db; } + + if (ini == null || !ini.TryGetKey("database.log", out string log)) { + DatabaseLog = null; + } else if (log.Length > 1 && (log[1] == ':' || log[0] == '/' || log[0] == '\\')) { + DatabaseLog = log; + } else { + DatabaseLog = App.DataPath + log; + } } public void Write() { using var file = new StreamWriter(FileName, false, Encoding.UTF8); - file.Write($"\n[database]\nfile = {DatabaseFile}\n"); + file.Write($"\r\n[database]\r\nfile = {DatabaseFile}\r\n"); + if (DatabaseLog != null) file.Write($"log = {DatabaseLog}\r\n"); } } }