LogPage.razor 1.74 KB
@page "/"
@inject IMemoryCache _memoryCache
@using AntDesign
@using AutomaticGrooveCalculationTool.Common.Utils
@using Microsoft.Extensions.Caching.Memory
@using Timer = System.Timers.Timer;

<Card Title="日志输出" Size="small">

    @if (!Logs.Any())
    {
        <Empty />
    }
    else
    {
        foreach (var item in Logs)
        {
            <Alert Message="@($"[{item.DateTime}]:{item.Message}")" Type="@item.StatusCode.ToString().ToLower()" ShowIcon="true" />
        }
    }
</Card>

@code
{
    private SystemLog log = SystemLog.Instance;
    private List<LogVM> Logs = new List<LogVM>();
    private readonly string CacheKey = "CacheKey_LogPage";
    private MemoryCacheEntryOptions cacheEntryOptions = null!;
    private Timer timer = new Timer(1);

    protected override void OnInitialized()
    {
        cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromHours(12));

        if (!_memoryCache.TryGetValue(CacheKey, out List<LogVM>? cacheValue))
        {
            cacheValue = new List<LogVM>();
            _memoryCache.Set(CacheKey, cacheValue, cacheEntryOptions);
        }
        Logs = cacheValue ?? new List<LogVM>();

        base.OnInitialized();
        timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
        timer.Start();
    }

    private void OnTimerCallback()
    {
        _ = InvokeAsync(() =>
        {
            var logItem = log.GetLog();
            if (logItem == null) return;
            Logs.Insert(0, logItem);
            if (Logs.Count > 30)
            {
                var lastItem = Logs.Last();
                Logs.Remove(lastItem);
            }
            _memoryCache.Set(CacheKey, Logs, cacheEntryOptions);
            StateHasChanged();
        });
    }
}