LANCommander/LANCommander.Server/UI/Pages/Settings/Logs/Components/LogViewer.razor
2026-01-18 18:56:01 -06:00

86 lines
2.5 KiB
Text

@using LANCommander.Server.Logging
@using Microsoft.AspNetCore.SignalR.Client
@using XtermBlazor
@inject ILogger<LogViewer> Logger
@inject MessageService MessageService
@inject NavigationManager NavigationManager
<Terminal @ref="_terminal" Options="_options" OnFirstRender="@OnFirstRender" />
@code {
Terminal? _terminal;
HubConnection? _hubConnection;
TerminalOptions _options = new()
{
CursorBlink = true,
CursorStyle = CursorStyle.Bar,
};
protected override async Task OnInitializedAsync()
{
try
{
await Connect();
}
catch (Exception ex)
{
Logger.LogError(ex, "Log viewer failed to connect");
MessageService.Error("Log viewer failed to connect");
}
}
async Task OnFirstRender()
{
if (_terminal is not null)
await _terminal.FitAsync();
}
async Task Connect()
{
_hubConnection = new HubConnectionBuilder()
.WithUrl(NavigationManager.ToAbsoluteUri("/logging"))
.Build();
_hubConnection.On<string, Microsoft.Extensions.Logging.LogLevel, DateTime>("Log", (message, level, timestamp) =>
{
string[] parts =
[
TerminalColor.BrightBlack,
"[",
TerminalColor.White,
timestamp.ToString("HH:mm:ss"),
TerminalColor.BrightBlack,
"]",
GetColorCode(level),
" ",
message,
TerminalColor.Default
];
_terminal?.WriteLine(String.Join("", parts));
});
await _hubConnection.StartAsync();
}
string GetColorCode(Microsoft.Extensions.Logging.LogLevel level)
{
return level switch
{
Microsoft.Extensions.Logging.LogLevel.Trace => TerminalColor.BrightBlack,
Microsoft.Extensions.Logging.LogLevel.Debug => TerminalColor.BrightCyan,
Microsoft.Extensions.Logging.LogLevel.Information => TerminalColor.BrightGreen,
Microsoft.Extensions.Logging.LogLevel.Warning => TerminalColor.BrightYellow,
Microsoft.Extensions.Logging.LogLevel.Error => TerminalColor.BrightRed,
Microsoft.Extensions.Logging.LogLevel.Critical => TerminalColor.BrightMagenta,
_ => TerminalColor.Default,
};
}
public async ValueTask DisposeAsync()
{
if (_hubConnection is not null)
await _hubConnection.DisposeAsync();
}
}