Add database log file
This commit is contained in:
@ -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<WineVar> WineVarieties { get; set; }
|
||||
public DbSet<Season> 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<bool> MgNrExists(int mgnr) {
|
||||
return await Members.FindAsync(mgnr) != null;
|
||||
}
|
||||
|
@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user