using Microsoft.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using XFEExtension.NetCore.XFEConsole;
using XFEWorkflow.Controls;
using XFEWorkflow.Infrastructure.Storage;
namespace XFEWorkflow.Views;
public sealed partial class LogViewPage : ManagementPage
{
public static LogViewPage? Current { get; private set; }
public LogViewPageViewModel ViewModel { get; } = new();
private readonly Pivot sections = new() { Height = 52 };
private readonly TextBox query = new() { PlaceholderText = "搜索消息、工作流、节点或运行 ID", Width = 300 };
private readonly ComboBox level = new() { Width = 132, ItemsSource = new[] { "全部级别", "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" }, SelectedIndex = 0 };
private readonly ComboBox workflows = new() { Width = 180 };
private readonly ComboBox range = new() { Width = 130, ItemsSource = new[] { "最近 7 天", "今天", "最近 30 天", "全部时间" }, SelectedIndex = 0 };
private readonly ToggleSwitch automatic = new() { OnContent = "自动刷新", OffContent = "自动刷新", IsOn = true };
private readonly ListView list = new() { SelectionMode = ListViewSelectionMode.Single };
private readonly StackPanel detail = new() { Spacing = 14 };
private readonly DetailsWorkspace panels = new("logs.details");
private readonly TextBlock empty = new() { Text = "没有匹配的日志", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .65, IsHitTestVisible = false };
private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(2) };
private readonly Button resetRun;
private WorkflowLogEntry[] visible = [];
private string category = "", runId = "";
private bool refreshing, updating;
public LogViewPage() : base("日志", "工作流运行、诊断与应用日志集中查看")
{
Current = this; InitializeComponent();
HeaderActions.Children.Add(ActionButton("刷新", RefreshAsync, "RefreshLogs")); HeaderActions.Children.Add(ActionButton("导出", ExportAsync, "ExportWorkflowLogs"));
foreach (var item in new[] { ("全部", ""), ("工作流运行", "工作流运行"), ("诊断", "诊断"), ("应用", "应用") }) sections.Items.Add(new PivotItem { Header = item.Item1, Tag = item.Item2 });
sections.SelectedIndex = 0;
var filters = new AdaptiveWrapPanel(); foreach (var control in new FrameworkElement[] { query, level, workflows, range, automatic }) filters.Children.Add(control);
resetRun = ActionButton("取消本次运行筛选", ClearRunFilterAsync, "ClearRunLogFilter"); resetRun.Visibility = Visibility.Collapsed; filters.Children.Add(resetRun);
var toolbar = new StackPanel { Spacing = 8 }; toolbar.Children.Add(sections); toolbar.Children.Add(filters); Toolbar.Children.Add(toolbar); Toolbar.SizeChanged += (_, e) => toolbar.Width = e.NewSize.Width;
list.ItemTemplateSelector = (DataTemplateSelector)Application.Current.Resources["WorkflowLogTemplates"]; list.ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"];
var master = new Grid(); master.Children.Add(list); master.Children.Add(empty); var card = Card(master); card.Padding = new(6); panels.Master.Content = card;
panels.Details.Content = Card(new ScrollViewer { Content = detail, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); Workspace.Children.Add(panels);
list.SelectionChanged += (_, _) => RenderDetails(); query.TextChanged += (_, _) => ApplyFilter();
foreach (var combo in new[] { level, workflows, range }) combo.SelectionChanged += (_, _) => { if (!updating) ApplyFilter(); };
sections.SelectionChanged += (_, _) => { category = (sections.SelectedItem as PivotItem)?.Tag as string ?? ""; ApplyFilter(); };
// XFEFileLog.Logs reads and parses its file. Poll through the background
// refresh instead of reading that property on the dispatcher to count it.
timer.Tick += async (_, _) => { if (automatic.IsOn) await Guard(RefreshAsync); };
Loaded += async (_, _) => { timer.Start(); await Guard(RefreshAsync); };
Unloaded += (_, _) => timer.Stop();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
runId = e.Parameter as string ?? ""; resetRun.Visibility = runId.Length == 0 ? Visibility.Collapsed : Visibility.Visible;
if (runId.Length > 0) { sections.SelectedIndex = 1; range.SelectedIndex = 3; }
}
private Task ClearRunFilterAsync() { runId = ""; resetRun.Visibility = Visibility.Collapsed; ApplyFilter(); return Task.CompletedTask; }
private sealed record WorkflowFilter(string Id, string Name);
private async Task RefreshAsync()
{
if (refreshing) return; refreshing = true;
try
{
await ViewModel.RefreshAsync();
var selected = (workflows.SelectedItem as WorkflowFilter)?.Id;
var options = new[] { new WorkflowFilter("", "全部工作流") }.Concat(ViewModel.Entries.Where(x => x.WorkflowId.Length > 0).DistinctBy(x => x.WorkflowId).Select(x => new WorkflowFilter(x.WorkflowId, x.WorkflowName))).ToArray();
updating = true; workflows.ItemsSource = options; workflows.DisplayMemberPath = "Name"; workflows.SelectedItem = options.FirstOrDefault(x => x.Id == selected) ?? options[0]; updating = false;
ApplyFilter();
}
finally { refreshing = false; }
}
private void ApplyFilter()
{
var selected = (list.SelectedItem as WorkflowLogEntry)?.Id;
var levels = new LogLevel?[] { null, LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warning, LogLevel.Error, LogLevel.Fatal };
var since = range.SelectedIndex switch { 1 => DateTime.Today, 2 => DateTime.Today.AddDays(-30), 3 => DateTime.MinValue, _ => DateTime.Today.AddDays(-7) };
var workflow = (workflows.SelectedItem as WorkflowFilter)?.Id;
visible = ViewModel.Filter(query.Text, category, levels[Math.Clamp(level.SelectedIndex, 0, levels.Length - 1)], string.IsNullOrEmpty(workflow) ? null : workflow, string.IsNullOrEmpty(runId) ? null : runId, since);
list.ItemsSource = visible; list.SelectedItem = visible.FirstOrDefault(x => x.Id == selected) ?? visible.FirstOrDefault();
empty.Visibility = visible.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
Status.Text = $"{visible.Length} 条 XFE 日志 · 已隐藏托管凭据" + (runId.Length == 0 ? "" : " · 运行 " + runId);
if (visible.Length == 0) RenderDetails();
}
private void RenderDetails()
{
detail.Children.Clear();
if (list.SelectedItem is not WorkflowLogEntry entry) { detail.Children.Add(Caption("选择日志查看完整消息与来源。")); return; }
detail.Children.Add(new TextBlock { Text = "日志详情", FontSize = 20, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold });
detail.Children.Add(Caption($"{entry.Time:yyyy-MM-dd HH:mm:ss.fff} · {entry.LevelLabel}"));
detail.Children.Add(Label("来源:" + entry.SourceLabel));
if (entry.RunId.Length > 0) { detail.Children.Add(Caption("运行 ID:" + entry.RunId)); detail.Children.Add(Label("触发方式:" + entry.Trigger)); }
if (entry.NodeId is { } node) detail.Children.Add(Caption("节点:" + (entry.NodeName.Length > 0 ? entry.NodeName : node)));
detail.Children.Add(new TextBox { AcceptsReturn = true, Text = entry.LogText, IsReadOnly = true, TextWrapping = TextWrapping.Wrap, MinHeight = 100, MaxHeight = 420 });
if (entry.RunId.Length > 0) detail.Children.Add(ActionButton("打开运行记录", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<RunsPage>(entry.RunId); return Task.CompletedTask; }, "OpenLogRun"));
if (entry.WorkflowId.Length > 0) detail.Children.Add(ActionButton("定位工作流 / 节点", () =>
{ AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<WorkflowEditorPage>(new Services.WorkflowNavigationTarget(entry.WorkflowId, entry.NodeId, entry.Diagnostic?.Line ?? 0, entry.Diagnostic?.Column ?? 0)); return Task.CompletedTask; }, "LocateLogWorkflow"));
}
private async Task ExportAsync()
{
var picker = new FileSavePicker { SuggestedFileName = "XFEWorkflow-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") };
picker.FileTypeChoices.Add("XFE 日志", new[] { ".log" }); picker.FileTypeChoices.Add("结构化日志", new[] { ".json" });
WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow));
if (await picker.PickSaveFileAsync() is not { } file) return;
var format = file.FileType.Equals(".json", StringComparison.OrdinalIgnoreCase) ? "json" : "log";
var entries = visible;
await Task.Run(() => WorkflowLogExporter.ExportAsync(file.Path, entries, format, false, Services.Redactor));
Status.Text = "已导出当前筛选的 XFE 日志";
}
}
using Microsoft.UI.Xaml.Navigation;
using Windows.Storage.Pickers;
using XFEExtension.NetCore.XFEConsole;
using XFEWorkflow.Controls;
using XFEWorkflow.Infrastructure.Storage;
namespace XFEWorkflow.Views;
public sealed partial class LogViewPage : ManagementPage
{
public static LogViewPage? Current { get; private set; }
public LogViewPageViewModel ViewModel { get; } = new();
private readonly Pivot sections = new() { Height = 52 };
private readonly TextBox query = new() { PlaceholderText = "搜索消息、工作流、节点或运行 ID", Width = 300 };
private readonly ComboBox level = new() { Width = 132, ItemsSource = new[] { "全部级别", "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" }, SelectedIndex = 0 };
private readonly ComboBox workflows = new() { Width = 180 };
private readonly ComboBox range = new() { Width = 130, ItemsSource = new[] { "最近 7 天", "今天", "最近 30 天", "全部时间" }, SelectedIndex = 0 };
private readonly ToggleSwitch automatic = new() { OnContent = "自动刷新", OffContent = "自动刷新", IsOn = true };
private readonly ListView list = new() { SelectionMode = ListViewSelectionMode.Single };
private readonly StackPanel detail = new() { Spacing = 14 };
private readonly DetailsWorkspace panels = new("logs.details");
private readonly TextBlock empty = new() { Text = "没有匹配的日志", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .65, IsHitTestVisible = false };
private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(2) };
private readonly Button resetRun;
private WorkflowLogEntry[] visible = [];
private string category = "", runId = "";
private bool refreshing, updating;
public LogViewPage() : base("日志", "工作流运行、诊断与应用日志集中查看")
{
Current = this; InitializeComponent();
HeaderActions.Children.Add(ActionButton("刷新", RefreshAsync, "RefreshLogs")); HeaderActions.Children.Add(ActionButton("导出", ExportAsync, "ExportWorkflowLogs"));
foreach (var item in new[] { ("全部", ""), ("工作流运行", "工作流运行"), ("诊断", "诊断"), ("应用", "应用") }) sections.Items.Add(new PivotItem { Header = item.Item1, Tag = item.Item2 });
sections.SelectedIndex = 0;
var filters = new AdaptiveWrapPanel(); foreach (var control in new FrameworkElement[] { query, level, workflows, range, automatic }) filters.Children.Add(control);
resetRun = ActionButton("取消本次运行筛选", ClearRunFilterAsync, "ClearRunLogFilter"); resetRun.Visibility = Visibility.Collapsed; filters.Children.Add(resetRun);
var toolbar = new StackPanel { Spacing = 8 }; toolbar.Children.Add(sections); toolbar.Children.Add(filters); Toolbar.Children.Add(toolbar); Toolbar.SizeChanged += (_, e) => toolbar.Width = e.NewSize.Width;
list.ItemTemplateSelector = (DataTemplateSelector)Application.Current.Resources["WorkflowLogTemplates"]; list.ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"];
var master = new Grid(); master.Children.Add(list); master.Children.Add(empty); var card = Card(master); card.Padding = new(6); panels.Master.Content = card;
panels.Details.Content = Card(new ScrollViewer { Content = detail, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); Workspace.Children.Add(panels);
list.SelectionChanged += (_, _) => RenderDetails(); query.TextChanged += (_, _) => ApplyFilter();
foreach (var combo in new[] { level, workflows, range }) combo.SelectionChanged += (_, _) => { if (!updating) ApplyFilter(); };
sections.SelectionChanged += (_, _) => { category = (sections.SelectedItem as PivotItem)?.Tag as string ?? ""; ApplyFilter(); };
// XFEFileLog.Logs reads and parses its file. Poll through the background
// refresh instead of reading that property on the dispatcher to count it.
timer.Tick += async (_, _) => { if (automatic.IsOn) await Guard(RefreshAsync); };
Loaded += async (_, _) => { timer.Start(); await Guard(RefreshAsync); };
Unloaded += (_, _) => timer.Stop();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
runId = e.Parameter as string ?? ""; resetRun.Visibility = runId.Length == 0 ? Visibility.Collapsed : Visibility.Visible;
if (runId.Length > 0) { sections.SelectedIndex = 1; range.SelectedIndex = 3; }
}
private Task ClearRunFilterAsync() { runId = ""; resetRun.Visibility = Visibility.Collapsed; ApplyFilter(); return Task.CompletedTask; }
private sealed record WorkflowFilter(string Id, string Name);
private async Task RefreshAsync()
{
if (refreshing) return; refreshing = true;
try
{
await ViewModel.RefreshAsync();
var selected = (workflows.SelectedItem as WorkflowFilter)?.Id;
var options = new[] { new WorkflowFilter("", "全部工作流") }.Concat(ViewModel.Entries.Where(x => x.WorkflowId.Length > 0).DistinctBy(x => x.WorkflowId).Select(x => new WorkflowFilter(x.WorkflowId, x.WorkflowName))).ToArray();
updating = true; workflows.ItemsSource = options; workflows.DisplayMemberPath = "Name"; workflows.SelectedItem = options.FirstOrDefault(x => x.Id == selected) ?? options[0]; updating = false;
ApplyFilter();
}
finally { refreshing = false; }
}
private void ApplyFilter()
{
var selected = (list.SelectedItem as WorkflowLogEntry)?.Id;
var levels = new LogLevel?[] { null, LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warning, LogLevel.Error, LogLevel.Fatal };
var since = range.SelectedIndex switch { 1 => DateTime.Today, 2 => DateTime.Today.AddDays(-30), 3 => DateTime.MinValue, _ => DateTime.Today.AddDays(-7) };
var workflow = (workflows.SelectedItem as WorkflowFilter)?.Id;
visible = ViewModel.Filter(query.Text, category, levels[Math.Clamp(level.SelectedIndex, 0, levels.Length - 1)], string.IsNullOrEmpty(workflow) ? null : workflow, string.IsNullOrEmpty(runId) ? null : runId, since);
list.ItemsSource = visible; list.SelectedItem = visible.FirstOrDefault(x => x.Id == selected) ?? visible.FirstOrDefault();
empty.Visibility = visible.Length == 0 ? Visibility.Visible : Visibility.Collapsed;
Status.Text = $"{visible.Length} 条 XFE 日志 · 已隐藏托管凭据" + (runId.Length == 0 ? "" : " · 运行 " + runId);
if (visible.Length == 0) RenderDetails();
}
private void RenderDetails()
{
detail.Children.Clear();
if (list.SelectedItem is not WorkflowLogEntry entry) { detail.Children.Add(Caption("选择日志查看完整消息与来源。")); return; }
detail.Children.Add(new TextBlock { Text = "日志详情", FontSize = 20, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold });
detail.Children.Add(Caption($"{entry.Time:yyyy-MM-dd HH:mm:ss.fff} · {entry.LevelLabel}"));
detail.Children.Add(Label("来源:" + entry.SourceLabel));
if (entry.RunId.Length > 0) { detail.Children.Add(Caption("运行 ID:" + entry.RunId)); detail.Children.Add(Label("触发方式:" + entry.Trigger)); }
if (entry.NodeId is { } node) detail.Children.Add(Caption("节点:" + (entry.NodeName.Length > 0 ? entry.NodeName : node)));
detail.Children.Add(new TextBox { AcceptsReturn = true, Text = entry.LogText, IsReadOnly = true, TextWrapping = TextWrapping.Wrap, MinHeight = 100, MaxHeight = 420 });
if (entry.RunId.Length > 0) detail.Children.Add(ActionButton("打开运行记录", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<RunsPage>(entry.RunId); return Task.CompletedTask; }, "OpenLogRun"));
if (entry.WorkflowId.Length > 0) detail.Children.Add(ActionButton("定位工作流 / 节点", () =>
{ AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<WorkflowEditorPage>(new Services.WorkflowNavigationTarget(entry.WorkflowId, entry.NodeId, entry.Diagnostic?.Line ?? 0, entry.Diagnostic?.Column ?? 0)); return Task.CompletedTask; }, "LocateLogWorkflow"));
}
private async Task ExportAsync()
{
var picker = new FileSavePicker { SuggestedFileName = "XFEWorkflow-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") };
picker.FileTypeChoices.Add("XFE 日志", new[] { ".log" }); picker.FileTypeChoices.Add("结构化日志", new[] { ".json" });
WinRT.Interop.InitializeWithWindow.Initialize(picker, WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow));
if (await picker.PickSaveFileAsync() is not { } file) return;
var format = file.FileType.Equals(".json", StringComparison.OrdinalIgnoreCase) ? "json" : "log";
var entries = visible;
await Task.Run(() => WorkflowLogExporter.ExportAsync(file.Path, entries, format, false, Services.Redactor));
Status.Text = "已导出当前筛选的 XFE 日志";
}
}