LogService.cs 1.4 KB
namespace IndustrialControl.Services;

public class LogService : IDisposable
{
    private readonly string _logsDir = Path.Combine(FileSystem.AppDataDirectory, "logs");
    private readonly TimeSpan _interval = TimeSpan.FromMilliseconds(800);
    private CancellationTokenSource? _cts;

    public event Action<string>? LogTextUpdated;

    public string TodayLogPath => Path.Combine(_logsDir, $"gr-{DateTime.Now:yyyy-MM-dd}.txt");

    public void Start()
    {
        Stop();
        _cts = new CancellationTokenSource();
        _ = Task.Run(() => LoopAsync(_cts.Token));
    }

    public void Stop()
    {
        _cts?.Cancel();
        _cts?.Dispose();
        _cts = null;
    }

    private async Task LoopAsync(CancellationToken token)
    {
        Directory.CreateDirectory(_logsDir);
        string last = string.Empty;
        while (!token.IsCancellationRequested)
        {
            try
            {
                if (File.Exists(TodayLogPath))
                {
                    var text = await File.ReadAllTextAsync(TodayLogPath, token);
                    if (!string.Equals(text, last, StringComparison.Ordinal))
                    {
                        last = text;
                        LogTextUpdated?.Invoke(text);
                    }
                }
            }
            catch { }
            await Task.Delay(_interval, token);
        }
    }

    public void Dispose() => Stop();
}