Updated App

Updated app to implement Serilog logging functionality.
Added GetAppFolder()
Changed GetSettingsPath() to use GetAppFolder()
Removed all Console.WriteLine() and replaed with Logger functions.
Created SetupLogger(), to log to both Console, and a Log file.
This commit is contained in:
Mario Steele 2025-07-31 16:17:06 -05:00
parent d8e650deec
commit 145c863fbe

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.Json;
using System.Threading;
@ -13,6 +14,10 @@ using FreeTubeSyncer.Library;
using FreeTubeSyncer.Models;
using FreeTubeSyncer.Models.DatabaseModels;
using FreeTubeSyncer.REST;
using Serilog;
using Serilog.Sinks.File.GzArchive;
using Serilog.Sinks.FileEx;
using Serilog.Sinks.SystemConsole.Themes;
namespace FreeTubeSyncer;
@ -45,6 +50,7 @@ public partial class App : Application
public override void OnFrameworkInitializationCompleted()
{
SetupLogger();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var path = "";
@ -59,7 +65,7 @@ public partial class App : Application
path = Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".var", "app", "io.freetubeapp.FreeTube", "config",
"FreeTube");
if (!Path.Exists(path))
Console.WriteLine("Failed to find Path for FreeTube!");
Log.Error("Failed to find Path for FreeTube!");
}
}
@ -112,9 +118,8 @@ public partial class App : Application
var path = GetSettingsPath();
if (!File.Exists(path))
{
var dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (!Directory.Exists(GetAppFolder()))
Directory.CreateDirectory(GetAppFolder());
}
File.WriteAllText(path, JsonSerializer.Serialize(_settings));
_settings!.SettingsDirty = false;
@ -129,20 +134,35 @@ public partial class App : Application
_settings = new AppSettings();
return;
}
var data = File.ReadAllText(path);
_settings = JsonSerializer.Deserialize<AppSettings>(data);
}
private string GetSettingsPath() => OperatingSystem.IsLinux()
? Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FreeTubeSyncer", "settings.json")
: Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "FreeTubeSyncer", "settings.json");
private string GetAppFolder() => Path.Join(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FreeTubeSyncer");
private string GetSettingsPath() => Path.Join(GetAppFolder(), "settings.json");
private void SetupLogger()
{
var path = Path.Join(GetAppFolder(), "logs");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var log = new LoggerConfiguration()
.WriteTo.Console(theme: AnsiConsoleTheme.Code,
outputTemplate: "[{Timestamp:hh:mm:ss t} {Level:u4}] {Message:lj}{NewLine}{Exception}")
.WriteTo.FileEx(Path.Join(path, "activity.log"), "MM-dd-yy",
rollingInterval: RollingInterval.Day,
outputTemplate: "[{Timestamp:MM/dd/yy - hh:mm:ss t}] [{Level:u4}] {Message:lj}{NewLine}{Exception}",
hooks: new FileArchiveRollingHooks(CompressionLevel.SmallestSize, path))
.CreateLogger();
Log.Logger = log;
Log.Information("Log Started.");
}
private async Task SyncMonitor()
{
// TODO: Replace with Logger
Console.WriteLine("Sync Monitor Starting Up.");
// TODO: Replace with Logger
Console.WriteLine("Starting API Validation Check.");
Log.Information("Sync Monitor Starting Up.");
Log.Information("Starting API Validation Check.");
while (_isRunning)
{
await _semaphoreSlim.WaitAsync();
@ -154,8 +174,7 @@ public partial class App : Application
continue;
}
// TODO: Replace with Logger
Console.WriteLine("Fetching initial data from Database.");
Log.Information("Fetching initial data from REST API.");
foreach (var syncer in _syncers!)
{
await syncer.FetchDatabase();
@ -167,8 +186,7 @@ public partial class App : Application
break;
}
// TODO: Replace with Logger
Console.WriteLine("Starting Filesystem Sync Monitoring.");
Log.Information("Starting Filesystem Sync Monitoring.");
var lastCheck = DateTime.Now;
while (_isRunning)
{
@ -179,13 +197,11 @@ public partial class App : Application
{
await _semaphoreSlim.WaitAsync();
var start = DateTime.Now;
// TODO: Replace with Logger
Console.WriteLine("Checking for updates...");
Log.Information("Checking for updates...");
var updateCheck = await _syncers[0].GetLastUpdated();
if (_lastUpdated < updateCheck)
{
// TODO: Replace with Logger
Console.WriteLine($"Update Found, fetching updates...");
Log.Information("Update Found, fetching updates...");
_lastUpdated = updateCheck;
foreach (var syncer in _syncers)
await syncer.FetchDatabase();
@ -193,8 +209,7 @@ public partial class App : Application
lastCheck = DateTime.Now;
var end = DateTime.Now - start;
_semaphoreSlim.Release();
// TODO: Replace with Logger
Console.WriteLine($"Check Completed. Total Time: {end}");
Log.Information("Check Completed. Total Time: {EndTime}", end);
continue;
}
@ -202,8 +217,7 @@ public partial class App : Application
var procs = Process.GetProcessesByName("FreeTube");
if (procs.Length > 0) continue;
// TODO: Replace with Logger
Console.WriteLine("FreeTube closed, and we have writes to make...");
Log.Information("FreeTube instance closed, and we have writes to make...");
await Task.Delay(1500);
await _semaphoreSlim.WaitAsync();
@ -212,71 +226,61 @@ public partial class App : Application
syncer.Sync();
var syncEnd = DateTime.Now - syncStart;
_semaphoreSlim.Release();
// TODO: Replace with Logger
Console.WriteLine($"Sync completed in {syncEnd}.");
Log.Information("Sync Completed. Total Time: {EndTime}", syncEnd);
}
// TODO: Replace with Logger
Console.WriteLine($"Filesystem Sync Monitor Shutdown.");
Log.Information("Filesystem Sync Monitor shutdown.");
}
private async void HandleSettingsChanged(object? sender, EventArgs e)
{
// TODO: Replace with Logger
Console.WriteLine("Settings have changed. Updating Settings...");
Log.Information("Settings have changed. Updating Settings...");
await _semaphoreSlim.WaitAsync();
var old = JsonSerializer.Deserialize<AppSettings>(_oldSettings!);
if (_settings!.RestBaseUrl != old!.RestBaseUrl)
{
// TODO: Replace with Logger
Console.WriteLine($"Updating syncers with new URL: {_settings.RestBaseUrl}.");
Log.Information("Updating syncers with new URL: {SettingsRestBaseUrl}.", _settings.RestBaseUrl);
foreach (var syncer in _syncers!)
syncer.UpdateBaseUrl(_settings.RestBaseUrl);
}
if (old.CheckInterval != _settings.CheckInterval)
{
// TODO: Replace with Logger
Console.WriteLine($"Updating Check Interval to {_settings.CheckInterval}.");
Log.Information("Updating Check Interval to {SettingsCheckInterval}.", _settings.CheckInterval);
_checkInterval = TimeSpan.FromSeconds(_settings.CheckInterval);
}
if (old.SyncHistory != _settings.SyncHistory)
{
// TODO: Replace with Logger
Console.WriteLine("History Syncer: " + (_settings.SyncHistory ? "Enabled" : "Disabled"));
Log.Information("History Syncer: {Status}",(_settings.SyncHistory ? "Enabled" : "Disabled"));
_historySyncer!.SetEnabled(_settings.SyncHistory);
await _historySyncer.FetchDatabase();
}
if (old.SyncPlaylist != _settings.SyncPlaylist)
{
// TODO: Replace with Logger
Console.WriteLine("Playlist Syncer: " + (_settings.SyncHistory ? "Enabled" : "Disabled"));
Log.Information("Playlist Syncer: {Status}",(_settings.SyncHistory ? "Enabled" : "Disabled"));
_playlistSyncer!.SetEnabled(_settings.SyncPlaylist);
await _playlistSyncer.FetchDatabase();
}
if (old.SyncProfile != _settings.SyncProfile)
{
// TODO: Replace with Logger
Console.WriteLine("Profile Syncer: " + (_settings.SyncHistory ? "Enabled" : "Disabled"));
Log.Information("Profile Syncer: {Status}", (_settings.SyncHistory ? "Enabled" : "Disabled"));
_profileSyncer!.SetEnabled(_settings.SyncProfile);
await _profileSyncer.FetchDatabase();
}
if (old.SyncSearchHistory != _settings.SyncSearchHistory)
{
// TODO: Replace with Logger
Console.WriteLine("Search History Syncer: " + (_settings.SyncHistory ? "Enabled" : "Disabled"));
Log.Information("Search History Syncer: {Status}", (_settings.SyncHistory ? "Enabled" : "Disabled"));
_searchHistorySyncer!.SetEnabled(_settings.SyncSearchHistory);
await _searchHistorySyncer.FetchDatabase();
}
if (old.SyncSettings != _settings.SyncSettings)
{
// TODO: Replace with Logger
Console.WriteLine("Settings Syncer: " + (_settings.SyncHistory ? "Enabled" : "Disabled"));
Log.Information("Settings Syncer: {Status}",(_settings.SyncHistory ? "Enabled" : "Disabled"));
_settingSyncer!.SetEnabled(_settings.SyncSettings);
await _settingSyncer.FetchDatabase();
}