LogPage.razor 1.64 KB
@page "/"

@using AntDesign
@using DataAcquisition.Common.Utils
@using Microsoft.Extensions.Caching.Memory
@using System.Collections.Concurrent

<Card Title="日志" Size="small">
    @if (!Logs.Any())
    {
        <Empty />
    }
    else
    {
        <Virtualize Items="@Logs.OrderByDescending(x => x.DateTime).ToList()" Context="log">
            <Alert Message="@($"[{log.DateTime}]:{log.Message}")" Type="@log.StatusCode.ToString().ToLower()" ShowIcon="true" />
        </Virtualize>
    }
</Card>

@code
{
    private SystemLog log = SystemLog.Instance;
    private static List<LogVM> Logs = new List<LogVM>();
    protected override void OnInitialized()
    {
        InitialLog();
        base.OnInitialized();
    }

    private void InitialLog()
    {
        _ = InvokeAsync(async () =>
        {
            int max = 30;
            while (true)
            {
                while (!log.IsEmpty)
                {
                    var newItem = log.GetLog();
                    if (newItem == null) continue;
                    var oldItem = Logs.Where(x => x.Message == newItem.Message).FirstOrDefault();
                    if (oldItem != null)
                    {
                        oldItem.DateTime = newItem.DateTime;
                    }
                    else
                    {
                        Logs.Add(newItem);
                    }
                }
                if (Logs.Count > max)
                {
                    Logs = Logs.OrderByDescending(x => x.DateTime).Take(max).ToList();
                }
                StateHasChanged();
                await Task.Delay(100);
            }
        });
    }
}