7 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 7bd2bf9df0 chore(release): bump to v1.2.0
Logging-overhaul release. Turns the v1.1 logging surface — working but
thin — into a diagnostic tool developers and end-users can rely on when
something misbehaves. No capture-engine changes, no breaking config
changes; Velopack publish on the existing `win` channel.

Highlights:
  - Runtime log-level picker in Settings (Debug / Info / Warn / Error)
  - Log viewer min-level filter + "Open folder" button
  - Caller context (File:Line:Member) on every entry, via
    CallerAwareLoggerExtensions
  - Global exception handlers for AppDomain / TaskScheduler /
    Avalonia dispatcher
  - Expanded coverage across WGC, hotkey, Velopack, tray,
    localization
  - 4 previously silent catches now log
  - settings.json schema bumped v1→v2 with auto migration
  - Window widened to 1200×720 with animated log drawer (480 px,
    200 ms fade + slide)
  - Scroll bars hidden on About + Settings (wheel scrolling still works)

Default minimum log level is now Information (was Debug) — flip back
to Debug via Settings → Logging if you were relying on verbose output.

Tests: 156 green (was 123). New suites cover InMemorySink,
SerilogLogLevelSwitcher, CallerAwareLoggerExtensions, LogViewer
filter / hydration / live-tail, and v1→v2 settings migration with
write-back.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:40:33 +07:00
poli0981andClaude Opus 4.7 7cd59eac36 feat(v1.2-M7): widen window, animate log drawer, hide main-view scrollbars
UX polish on top of the M1–M5 logging work:

- **Window 1200×720** (was 960×600) with **log drawer at 480 px**
  (was 400 px). Content area visible while the drawer is open goes
  from ~340 px to ~500 px — the cramped "half your app is behind a
  drawer" feeling is gone.
- **Log drawer slides in with a 200 ms fade + translate-X easing.**
  The drawer is now kept in the visual tree permanently so
  transitions fire on every toggle. Classes.visible is bound to
  IsLogViewerVisible; IsHitTestVisible is bound to the same flag so
  the drawer stays click-through while hidden. DoubleTransition
  (Opacity, 180 ms) + TransformOperationsTransition (translateX,
  220 ms) with CircularEaseOut.
- **Scroll bars hidden on About + Settings** (Horizontal=Disabled,
  Vertical=Hidden). Mouse-wheel scrolling still works; the track
  just isn't drawn. Update log + Log viewer drawer keep their bars
  since those are diagnostic surfaces where users want to scrub.

Dashboard has no ScrollViewer so it wasn't touched. UpdateView's
inner log ScrollViewer is left alone for the same reason as the log
drawer: it's a diagnostic surface.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:39:57 +07:00
poli0981andClaude Opus 4.7 f82b300d25 test(v1.2-M5): unit coverage for logging stack + v1→v2 settings migration
New test suites:
  - InMemorySinkTests (7 cases): ring-buffer eviction at MaxCapacity,
    pause suppresses Emitted but still buffers, Snapshot returns a
    defensive copy, Clear empties, caller properties round-trip when
    present on the LogEvent and stay null when absent
  - SerilogLogLevelSwitcherTests (13 cases): canonical + alias names
    (info/warn/ERROR/empty) map correctly, unknown/null falls back
    to Information, CurrentLevel reports canonical capitalisation
  - CallerAwareLoggerExtensionsTests (4 cases): LogXAt extensions
    attach Member/File/Line as scope state, Path.GetFileName strips
    absolute build-machine paths, exception overloads forward both
    exception and caller context, template args pass through
  - LogViewerViewModelTests (6 cases): hydration copies snapshot
    (idempotent), live tail appends, filter rebuild keeps only ≥
    selected level, filter never touches the underlying buffer, live
    tail below filter is suppressed

Extended JsonSettingsStoreTests:
  - V1File_MigratesToV2AndWritesBack: v1 document without LogLevel is
    upgraded in memory AND the canonical v2 form is written back to
    disk
  - V2File_PreservesLogLevelField: existing LogLevel value round-trips

Also tightened JsonSettingsStore migration: STJ source-gen does NOT
honour record init defaults when a property is absent from JSON, so
we set LogLevel explicitly in the v1→v2 branch and add a defensive
"v2 file with null LogLevel" fill-in (possible via hand-edits).

Totals: 156 tests (was 123), all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:24:00 +07:00
poli0981andClaude Opus 4.7 e6ba7b4dfa feat(v1.2-M4): runtime log-level switch + viewer filter + reveal folder
User-facing logging controls:

Settings → Logging group adds a "Minimum log level" picker bound to a new
AppSettings.LogLevel field (schema v1→v2, additive). Changing the picker
updates a Serilog LoggingLevelSwitch live — no restart — and persists to
settings.json through the debounced writer. Default is "Information";
legacy v1 users migrate in place and keep their existing values
(LogLevel defaults when deserialised). Hand-edited or unknown values
fall back to Information with a log line at startup.

LogViewer gets two new controls in the header:
  - Min-level filter dropdown (view-side only — sink keeps everything,
    so Export always carries the full history regardless of filter)
  - "Open folder" button that launches Explorer at
    %LocalAppData%\CaptureImage\logs, with a Toast on failure

Plumbing:
  - LoggingSetup.Initialize now returns (InMemorySink, LoggingLevelSwitch);
    Program wires the switch to settings.Current.LogLevel after LoadAsync.
    Boot floor stays at Debug so early-startup lines always reach the
    rolling file.
  - CompositionRoot adds LoggingLevelSwitch singleton + the new
    ILogLevelSwitcher abstraction (Core) backed by SerilogLogLevelSwitcher
    (Infrastructure). Keeps VMs free of a Serilog dependency.
  - MEL minimum level goes to Trace so filtering stays with the Serilog
    switch.
  - LogPaths.GetLogsDirectory (new Core helper) — single source of truth
    for %LocalAppData%\CaptureImage\logs, used by both LoggingSetup and
    LogViewerViewModel's Reveal command.
  - JsonSettingsStore: v1→v2 migration stamps the new version and writes
    back on load so existing users don't need to touch settings.json.
  - SettingsJsonContext needs no change — LogLevel is a string.

Localization: new keys Settings_Logging, Settings_LogLevel,
Settings_LogLevelHint, Log_Filter, Log_RevealFolder added in EN / VI / AR.
Arabic / Vietnamese remain machine-assisted per existing disclaimer.

Tests updated: JsonSettingsStoreTests now expect Version=2 and assert the
new LogLevel default.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:19:51 +07:00
poli0981andClaude Opus 4.7 3ae8fdddfe feat(v1.2-M3): expand logging coverage across capture/hotkey/update/tray/localization
Fill in log call sites that were either silent or shallow:

- WindowsGraphicsCaptureEngine: Info on session start (HWND + size), Debug on
  first frame arrival and session dispose, Warning on CreateForWindow
  COMException with explicit HRESULT formatting, Warning on frame timeout
  with configured deadline, dedicated COMException path on outer catch
- HotkeyConflictSniffer: Win32 error codes now decode to names
  (ERROR_HOTKEY_ALREADY_REGISTERED / ERROR_INVALID_PARAMETER / etc.) so
  debug output reads without Googling 1409
- SharpHookHotkeyService: Info when TaskPoolGlobalHook actually starts
  (previously only logged on Stop + binding change)
- VelopackUpdateService: Info before ApplyUpdatesAndRestart with target
  version + Error if the call throws (it used to fail silently into the
  relaunch)
- AvaloniaTrayIconHost: wrap BuildRuntimeIcon (SkiaSharp) in a guarded
  helper so a native-asset blow-up falls back to Avalonia's default glyph
  instead of crashing startup; Info when the tray is initialized and
  disposed
- ResxLocalizationService: inject ILogger and dedup-log Warning on the
  first time a resource key is missing per (culture, key) pair — catches
  resx typos without flooding the file on every refresh
- Program.cs: startup banner now includes Version / OS / Culture / Args
  so support sessions can pick the build up from a glance

Also extend CallerAwareLoggerExtensions with LogWarningAt<T0>,
LogWarningAt<T0,T1> exception overloads and LogErrorAt<T0,T1> to cover
the new WGC call sites. Update ResxLocalizationServiceTests to pass
NullLogger through the new required ctor parameter.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:04:53 +07:00
poli0981andClaude Opus 4.7 2367082aab feat(v1.2-M2): caller-aware logger extensions with file:line context
Add LogXAt extensions on ILogger that capture [CallerMemberName],
[CallerFilePath], [CallerLineNumber] and attach them as Serilog properties
(Member / File / Line) via MEL BeginScope, which the Serilog MEL bridge
forwards as LogEvent properties. Path.GetFileName strips build-machine
paths so we don't leak E:\capture\captureimg\... into shipped logs.

Pipeline plumbed end-to-end:
  - LogEntry gains File / Line / Member init-only properties + FileLineText
    computed helper for the viewer
  - InMemorySink.MapToEntry reads the three scalar properties
  - CallerPropertyDefaultsEnricher injects empty defaults so the rolling-
    file template renders cleanly on legacy call sites
  - Rolling-file outputTemplate gains ({File}:{Line}) between level and
    message
  - LogViewer gets a subdued File:Line column; Export file format matches
    the rolling file

Overloads cover 0-3 template args for Info/Debug/Warning, plus Error
variants that take an Exception. Existing ILogger<T>.LogX call sites keep
working unchanged (no caller context, rendered as legacy defaults).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 08:59:26 +07:00
poli0981andClaude Opus 4.7 b72d9d9e22 fix(v1.2-M1): global exception handlers + unswallow silent catches
Register AppDomain.UnhandledException, TaskScheduler.UnobservedTaskException,
and Avalonia Dispatcher.UnhandledException handlers in Program.cs so background-
thread and UI-dispatcher crashes reach the rolling log instead of silently
tearing down the process. Structured log on each path with IsTerminating flag,
SetObserved() on unobserved tasks, Handled=true on dispatcher exceptions.

Unswallow four silent catches that hid real failures:
  - SharpHookHotkeyService.Stop/Dispose: log at Warning when hook dispose throws
  - WmiProcessWatcher.DisposeWatchers_NoLock: log at Debug on teardown failures
  - JsonSettingsStore.Deserialize: log JsonException with line/byte position
    before returning null (caller still falls back to defaults)
  - JsonSettingsStore.TryDelete: log at Debug when temp-file cleanup fails

Also add shutdown marker in finally (Reason=Normal|StartupCrash) so logs
bracket every session.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 08:54:03 +07:00
36 changed files with 1690 additions and 74 deletions

No files matched your search

+90
View File
@@ -7,6 +7,96 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.2.0] - 2026-04-21
Logging overhaul. Turns a working-but-thin diagnostic surface into one you
can actually rely on when things go wrong — developer and end-user alike.
No capture-engine changes; Velopack release on the existing `win` channel
so the delta chain from v1.1.2 stays intact.
### Added
- **Runtime log-level control.** New Settings → Logging group with a
minimum-level picker (Debug / Information / Warning / Error).
Persisted in `AppSettings.LogLevel` (new field, schema bump v1 → v2,
additive) and pushed into Serilog's `LoggingLevelSwitch` live — no
restart required.
- **Log viewer min-level filter.** Dropdown in the log drawer header
narrows what's shown without touching the sink buffer, so Export
still carries the full history regardless of the filter.
- **"Open folder" button in the log drawer.** Launches Explorer at
`%LocalAppData%\CaptureImage\logs` for support-session copy-paste.
Guarded with a Toast on failure.
- **Caller context on every log entry** — each line carries `File`,
`Line`, and `Member` structured properties, captured via new
`LogInformationAt` / `LogWarningAt` / `LogErrorAt` / `LogDebugAt`
extension methods on `ILogger`. Rolling-file template now prints
`(File.cs:42)`; log viewer shows a subdued `File:Line` column; Export
includes the same. Absolute build-machine paths are stripped via
`Path.GetFileName` so shipped logs stay clean.
- **Global exception handlers.** `AppDomain.UnhandledException`,
`TaskScheduler.UnobservedTaskException`, and
`Dispatcher.UIThread.UnhandledException` all now reach Serilog before
the process dies or the UI resumes. `SetObserved()` on unobserved
task exceptions keeps the default-crash policy from ending the app on
background-thread throws.
- **Startup + shutdown banner** — Program.Main logs
`Version` / `OS` / `Culture` / `Args` on start and a
`Reason=Normal|StartupCrash` line on exit, so support sessions can
tell which build produced the log at a glance.
- **Expanded coverage** — `Windows.Graphics.Capture` engine emits Info
on session start, Debug on first frame + session dispose, Warning on
frame timeout, Error with explicit `HRESULT=0x…` on `COMException`;
`HotkeyConflictSniffer` decodes Win32 error codes by name
(`ERROR_HOTKEY_ALREADY_REGISTERED` / `ERROR_INVALID_PARAMETER` / …);
`SharpHookHotkeyService` logs when `TaskPoolGlobalHook` boots;
`VelopackUpdateService` logs before + after
`ApplyUpdatesAndRestart`; `AvaloniaTrayIconHost` logs tray
init/dispose and guards the runtime SkiaSharp icon render so a
native-asset blow-up falls back to the platform default instead of
crashing startup; `ResxLocalizationService` warns once per
`(culture, key)` pair when a resource key is missing (dedup
prevents flooding on every refresh).
### Changed
- **Window widened to 1200×720** (was 960×600) and **log drawer
widened to 480 px** (was 400 px). The drawer now slides in with a
200 ms fade + 48 px translate-X easing (`CircularEaseOut`) instead
of snapping in and out. Content area visible while the drawer is
open is now ~500 px (was ~340 px).
- **Scroll bars hidden on About + Settings tabs.** Mouse-wheel
scrolling still works; the track is just no longer drawn, so the
view reads cleanly on the fixed-size window. Horizontal scrolling
on those tabs is disabled entirely. Diagnostic surfaces (Update
log, Log viewer drawer) keep their visible bars.
- **Default minimum log level is now `Information`** (was `Debug`).
v1 users are migrated in place: `settings.json` is stamped
Version=2 on first v1.2 launch and the LogLevel field defaults to
`Information`. Flip back to Debug via Settings → Logging if you
were relying on verbose output.
- Four previously-silent `catch { /* ignore */ }` blocks now log
their exceptions: `SharpHookHotkeyService.Stop/Dispose` (Warning),
`WmiProcessWatcher.DisposeWatchers_NoLock` (Debug),
`JsonSettingsStore.Deserialize` (Warning with JSON line / byte
position), `JsonSettingsStore.TryDelete` (Debug).
### Migration
- **`settings.json` schema v1 → v2.** Automatic on first v1.2 run —
the file is re-written in canonical v2 form with `LogLevel =
"Information"` and existing values preserved. Hand-edited files
with `logLevel` already present keep their value.
### Tests
- 33 new unit tests (total 156, up from 123). Covers the
`InMemorySink` ring buffer / pause / clear / snapshot-copy
semantics, `SerilogLogLevelSwitcher` string mapping + fallback,
`CallerAwareLoggerExtensions` scope + path-stripping behaviour,
`LogViewerViewModel` hydration / filter / live-tail paths, and the
v1 → v2 settings migration with write-back.
## [1.1.2] - 2026-04-20
Localization hotfix on top of v1.1.1 — closes 13 bugs and gaps found in
+2 -2
View File
@@ -10,9 +10,9 @@
<UseWpf>false</UseWpf>
<!-- App icon + manifest are added in M4 -->
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<!-- Release value for v1.1.2; release.yml still overrides via /p:Version=<git-tag>
<!-- Release value for v1.2.0; release.yml still overrides via /p:Version=<git-tag>
for tag-driven builds. Bump to the next -dev suffix after the release lands. -->
<Version>1.1.2</Version>
<Version>1.2.0</Version>
</PropertyGroup>
<ItemGroup>
+9 -2
View File
@@ -21,6 +21,7 @@ using CaptureImage.ViewModels.Update;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Extensions.Logging;
namespace CaptureImage.App;
@@ -30,7 +31,7 @@ namespace CaptureImage.App;
/// </summary>
internal static class CompositionRoot
{
public static IServiceProvider BuildServices(InMemorySink inMemorySink)
public static IServiceProvider BuildServices(InMemorySink inMemorySink, LoggingLevelSwitch loggingLevelSwitch)
{
var services = new ServiceCollection();
@@ -39,13 +40,19 @@ internal static class CompositionRoot
{
builder.ClearProviders();
builder.AddProvider(new SerilogLoggerProvider(Log.Logger, dispose: false));
builder.SetMinimumLevel(LogLevel.Debug);
// MEL's minimum level needs to sit at Trace/Debug so it never filters events
// before they reach Serilog — the real gating happens in the LoggingLevelSwitch.
builder.SetMinimumLevel(LogLevel.Trace);
});
// The same InMemorySink instance is both the Serilog sink AND the log buffer source
// used by the log viewer VM.
services.AddSingleton(inMemorySink);
services.AddSingleton<ILogBufferSource>(inMemorySink);
// Expose the Serilog level switch so Settings can mutate it live. Wrap it in the
// ILogLevelSwitcher abstraction so ViewModels don't take a Serilog dependency.
services.AddSingleton(loggingLevelSwitch);
services.AddSingleton<ILogLevelSwitcher, SerilogLogLevelSwitcher>();
// --- Cross-cutting -----------------------------------------------------
services.AddSingleton<IFileSystem, FileSystem>();
+38 -12
View File
@@ -1,5 +1,7 @@
using CaptureImage.Core.Logging;
using CaptureImage.Infrastructure.Logging;
using Serilog;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.App;
@@ -22,26 +24,30 @@ internal static class LoggingSetup
return dir;
}
public static string GetLogsDir()
{
var dir = Path.Combine(GetAppDataDir(), "logs");
Directory.CreateDirectory(dir);
return dir;
}
public static string GetLogsDir() => LogPaths.GetLogsDirectory();
/// <summary>
/// Build the Serilog root logger together with the in-memory sink, and assign it to
/// <see cref="Log.Logger"/>. Returns the sink so the DI container can register it.
/// Build the Serilog root logger together with the in-memory sink and the runtime
/// level switch, and assign the logger to <see cref="Log.Logger"/>. Both are returned
/// so the DI container can register them — the sink drives the log viewer, the switch
/// drives the Settings → Log Level picker.
/// </summary>
public static InMemorySink Initialize()
/// <remarks>
/// The switch boots at <see cref="LogEventLevel.Debug"/> so early-startup telemetry is
/// always captured; <c>Program.Main</c> narrows it to the user's configured value once
/// <c>ISettingsStore.LoadAsync</c> has finished.
/// </remarks>
public static (InMemorySink Sink, LoggingLevelSwitch LevelSwitch) Initialize()
{
var logPath = Path.Combine(GetLogsDir(), "captureimg-.log");
var sink = new InMemorySink();
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Debug);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.ControlledBy(levelSwitch)
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.WithProperty("App", "CaptureImage")
.Enrich.With(new CallerPropertyDefaultsEnricher())
.WriteTo.Console()
.WriteTo.Sink(sink)
.WriteTo.Async(a => a.File(
@@ -51,9 +57,29 @@ internal static class LoggingSetup
fileSizeLimitBytes: 10L * 1024 * 1024,
rollOnFileSizeLimit: true,
shared: false,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"))
// {File}:{Line} shows caller context injected by CallerAwareLoggerExtensions.
// Missing on legacy call sites — Serilog prints a bare ":" then, so keep the
// template consistent and accept that one cosmetic artifact until those are
// migrated. {Properties:j} still JSON-dumps every non-templated property.
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] ({File}:{Line}) {Message:lj} {Properties:j}{NewLine}{Exception}"))
.CreateLogger();
return sink;
return (sink, levelSwitch);
}
/// <summary>
/// Map the persisted <c>LogLevel</c> string (one of <c>Debug</c> / <c>Information</c> /
/// <c>Warning</c> / <c>Error</c>) to a <see cref="LogEventLevel"/>. Unknown strings
/// fall back to <see cref="LogEventLevel.Information"/>.
/// </summary>
public static LogEventLevel ParseLevel(string? value) => value?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
+65 -5
View File
@@ -1,6 +1,7 @@
using System;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Threading;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
@@ -27,20 +28,38 @@ internal static class Program
// when the launch is a normal one.
VelopackApp.Build().Run();
// Bootstrap Serilog early (and keep the in-memory sink reference for DI).
var inMemorySink = LoggingSetup.Initialize();
// Bootstrap Serilog early (keep the in-memory sink + runtime level switch for DI).
var (inMemorySink, loggingLevelSwitch) = LoggingSetup.Initialize();
// Catch anything that escapes try/catch on any thread. Register before we stand up DI
// or UI so background-thread crashes during startup still reach the rolling file.
RegisterGlobalExceptionHandlers();
var shutdownReason = "Normal";
try
{
Log.Information("CaptureImage starting. Args: {Args}", args);
Log.Information(
"CaptureImage starting. Version={Version} OS={OS} Culture={Culture} Args={Args}",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0-dev",
System.Runtime.InteropServices.RuntimeInformation.OSDescription,
System.Globalization.CultureInfo.CurrentUICulture.Name,
args);
var services = CompositionRoot.BuildServices(inMemorySink);
var services = CompositionRoot.BuildServices(inMemorySink, loggingLevelSwitch);
UI.App.Services = services;
// Load persisted settings before the UI binds to them.
var settingsStore = services.GetRequiredService<ISettingsStore>();
settingsStore.LoadAsync().GetAwaiter().GetResult();
// Narrow Serilog's minimum level from the boot default (Debug) down to whatever
// the user chose via Settings last run. This happens after LoadAsync so that
// early-startup lines — "CaptureImage starting", "Settings loaded …" — always
// land in the file regardless of the configured floor.
var configuredLevel = LoggingSetup.ParseLevel(settingsStore.Current.LogLevel);
loggingLevelSwitch.MinimumLevel = configuredLevel;
Log.Information("Log level set to {Level} from settings.", configuredLevel);
// Apply persisted culture before the first window is constructed so nav labels etc.
// render in the right language from frame zero. Only accept cultures the app
// actually ships translations for — a hand-edited settings.json with, say,
@@ -86,6 +105,7 @@ internal static class Program
}
catch (Exception ex)
{
shutdownReason = "StartupCrash";
Log.Fatal(ex, "CaptureImage crashed during startup.");
return -1;
}
@@ -107,6 +127,7 @@ internal static class Program
{
Log.Warning(ex, "Failed to flush settings on shutdown.");
}
Log.Information("CaptureImage shutting down. Reason={Reason}", shutdownReason);
Log.CloseAndFlush();
}
}
@@ -118,5 +139,44 @@ internal static class Program
=> AppBuilder.Configure<UI.App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
.LogToTrace()
.AfterSetup(_ =>
{
// Hook the Avalonia UI-thread dispatcher so exceptions raised by command
// handlers, bindings, and tick callbacks don't silently kill the UI.
Dispatcher.UIThread.UnhandledException += OnDispatcherUnhandledException;
});
private static void RegisterGlobalExceptionHandlers()
{
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
{
var ex = e.ExceptionObject as Exception;
Log.Fatal(
ex,
"Unhandled AppDomain exception. IsTerminating={IsTerminating}",
e.IsTerminating);
if (e.IsTerminating)
{
// Last-ditch flush — CLR is about to pull the rug.
Log.CloseAndFlush();
}
};
TaskScheduler.UnobservedTaskException += (_, e) =>
{
Log.Error(e.Exception, "Unobserved task exception.");
// Claim the exception so the default .NET policy doesn't terminate the process
// on the next GC — structured log is enough signal for us to investigate.
e.SetObserved();
};
}
private static void OnDispatcherUnhandledException(object? sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.Error(e.Exception, "Unhandled exception on UI dispatcher.");
// Don't let a single bad command tear down the window — swallow after logging so the
// user can keep using the app (and notice the Toast / LogViewer will surface it).
e.Handled = true;
}
}
@@ -0,0 +1,21 @@
namespace CaptureImage.Core.Abstractions;
/// <summary>
/// Live control over the Serilog minimum-level floor. The Settings view mutates this
/// when the user picks a new log level, and the wrapper — implemented in
/// <c>CaptureImage.Infrastructure.Logging</c> — pushes the value through to Serilog's
/// <c>LoggingLevelSwitch</c> so new events are filtered immediately.
/// </summary>
/// <remarks>
/// Level strings accepted by <see cref="SetLevel"/>: <c>Debug</c>, <c>Information</c>,
/// <c>Warning</c>, <c>Error</c> (case-insensitive, aliases <c>info</c> / <c>warn</c>
/// accepted). Unknown strings fall back to <c>Information</c>.
/// </remarks>
public interface ILogLevelSwitcher
{
/// <summary>Set the minimum log level from a canonical string.</summary>
void SetLevel(string level);
/// <summary>Canonical name of the currently active minimum level.</summary>
string CurrentLevel { get; }
}
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Logging;
namespace CaptureImage.Core.Logging;
/// <summary>
/// Extension methods that inject <c>[CallerMemberName]</c>, <c>[CallerFilePath]</c>, and
/// <c>[CallerLineNumber]</c> as Serilog structured properties (<c>Member</c>, <c>File</c>,
/// <c>Line</c>) so every entry the log viewer shows — and every line the rolling file
/// receives — carries a cheap jump-to-source anchor.
/// </summary>
/// <remarks>
/// <para>
/// The properties are attached via <see cref="ILogger.BeginScope{TState}"/>. The
/// <c>Serilog.Extensions.Logging</c> provider forwards MEL scope state as
/// <see cref="Serilog.Events.LogEvent"/> properties, so the output template
/// <c>{File}:{Line}</c> and the <see cref="Models.LogEntry"/> mapper both see them.
/// </para>
/// <para>
/// <c>Path.GetFileName</c> strips the build-machine absolute path so we don't leak
/// <c>E:\capture\captureimg\…</c> into shipped binaries and user log exports.
/// </para>
/// <para>
/// Overloads are provided for 0–3 template arguments — that covers the vast majority of
/// call sites. For more arguments, fall back to <see cref="ILogger.BeginScope{TState}"/>
/// with a manual scope and regular <c>LogInformation</c>/<c>LogError</c>/etc.
/// </para>
/// </remarks>
public static class CallerAwareLoggerExtensions
{
// --- Information --------------------------------------------------------
public static void LogInformationAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(message);
}
}
public static void LogInformationAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0);
}
}
public static void LogInformationAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1);
}
}
public static void LogInformationAt<T0, T1, T2>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
T2 arg2,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogInformation(messageTemplate, arg0, arg1, arg2);
}
}
// --- Debug --------------------------------------------------------------
public static void LogDebugAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(message);
}
}
public static void LogDebugAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0);
}
}
public static void LogDebugAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogDebug(messageTemplate, arg0, arg1);
}
}
// --- Warning ------------------------------------------------------------
public static void LogWarningAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(message);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(messageTemplate, arg0, arg1);
}
}
public static void LogWarningAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate);
}
}
public static void LogWarningAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0);
}
}
public static void LogWarningAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogWarning(exception, messageTemplate, arg0, arg1);
}
}
// --- Error --------------------------------------------------------------
public static void LogErrorAt(
this ILogger logger,
string message,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(message);
}
}
public static void LogErrorAt(
this ILogger logger,
Exception exception,
string messageTemplate,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate);
}
}
public static void LogErrorAt<T0>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0);
}
}
public static void LogErrorAt<T0, T1>(
this ILogger logger,
Exception exception,
string messageTemplate,
T0 arg0,
T1 arg1,
[CallerMemberName] string member = "",
[CallerFilePath] string filePath = "",
[CallerLineNumber] int line = 0)
{
using (logger.BeginScope(CallerScope(member, filePath, line)))
{
logger.LogError(exception, messageTemplate, arg0, arg1);
}
}
// --- Shared scope builder -----------------------------------------------
private static Dictionary<string, object> CallerScope(string member, string filePath, int line)
=> new(3)
{
["Member"] = member ?? string.Empty,
// Path.GetFileName tolerates forward and back slashes, returns the input if the
// string doesn't look like a path — so empty / odd CallerFilePath values degrade
// gracefully.
["File"] = string.IsNullOrEmpty(filePath) ? string.Empty : Path.GetFileName(filePath),
["Line"] = line,
};
}
+27
View File
@@ -0,0 +1,27 @@
using System;
using System.IO;
namespace CaptureImage.Core.Logging;
/// <summary>
/// Canonical on-disk locations for log files. Shared between <c>LoggingSetup</c> (which
/// configures Serilog's rolling-file sink) and <c>LogViewerViewModel</c> (which opens the
/// folder when the user clicks "Reveal logs folder") so both agree on the path.
/// </summary>
public static class LogPaths
{
/// <summary>
/// Returns <c>%LocalAppData%\CaptureImage\logs</c>, creating the directory tree if
/// missing. Uses <see cref="Environment.SpecialFolder.LocalApplicationData"/> so the
/// path is per-user and roams with the profile.
/// </summary>
public static string GetLogsDirectory()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"CaptureImage",
"logs");
Directory.CreateDirectory(dir);
return dir;
}
}
+14 -1
View File
@@ -19,7 +19,7 @@ namespace CaptureImage.Core.Models;
public sealed record AppSettings
{
/// <summary>Schema version. Bump when adding migration steps.</summary>
public int Version { get; init; } = 1;
public int Version { get; init; } = 2;
/// <summary>
/// IETF BCP-47 culture code for UI (e.g. <c>en-US</c>, <c>vi-VN</c>, <c>ar-SA</c>).
@@ -34,6 +34,19 @@ public sealed record AppSettings
public CaptureSettings Capture { get; init; } = new();
public UiSettings UI { get; init; } = new();
/// <summary>
/// Minimum log level retained in the rolling file and in-memory buffer.
/// One of <c>Debug</c>, <c>Information</c>, <c>Warning</c>, <c>Error</c> — case-insensitive
/// on parse. Unknown values fall back to <c>Information</c>.
/// </summary>
/// <remarks>
/// Stored as a string rather than an enum so hand-edited <c>settings.json</c> files stay
/// readable and so the persistence layer doesn't take a dependency on MEL's enum identity.
/// v1 files load with this defaulted to <c>Information</c>; legacy behaviour was
/// <c>Debug</c>, so users who relied on it get a note in CHANGELOG to flip it back.
/// </remarks>
public string LogLevel { get; init; } = "Information";
}
/// <summary>Capture-specific persisted options.</summary>
+27 -1
View File
@@ -9,12 +9,38 @@ namespace CaptureImage.Core.Models;
/// <param name="SourceContext">Fully-qualified logger name if present, else empty.</param>
/// <param name="Message">Rendered message text (format tokens already applied).</param>
/// <param name="Exception">Exception stringification if any, else null.</param>
/// <remarks>
/// The <see cref="File"/>, <see cref="Line"/>, and <see cref="Member"/> init-only properties are
/// populated when the call site used the <c>LogXAt</c> helpers from
/// <c>CaptureImage.Core.Logging.CallerAwareLoggerExtensions</c>; they stay null for legacy
/// call sites that still log via <c>ILogger&lt;T&gt;.LogInformation</c> or the static
/// <c>Serilog.Log</c> API.
/// </remarks>
public sealed record LogEntry(
DateTimeOffset Timestamp,
LogLevel Level,
string SourceContext,
string Message,
string? Exception);
string? Exception)
{
/// <summary>Source file name (e.g. <c>WindowsGraphicsCaptureEngine.cs</c>) — no directory.</summary>
public string? File { get; init; }
/// <summary>Line number in <see cref="File"/> where the log was emitted.</summary>
public int? Line { get; init; }
/// <summary>Method or property name that emitted the log.</summary>
public string? Member { get; init; }
/// <summary>
/// Convenience string for the log viewer — <c>"File.cs:42"</c> when both are present,
/// else empty. Computed; never participates in record equality.
/// </summary>
public string FileLineText =>
!string.IsNullOrEmpty(File) && Line is > 0
? $"{File}:{Line}"
: string.Empty;
}
/// <summary>Levels the log viewer filters on. Mapped from Serilog's LogEventLevel.</summary>
public enum LogLevel
@@ -1,6 +1,8 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Errors;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using Microsoft.Extensions.Logging;
using Vortice.Direct3D11;
@@ -69,14 +71,29 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
{
item = CaptureItemInterop.CreateForWindow(target.WindowHandle);
}
catch (COMException comEx)
{
_logger.LogWarningAt(
comEx,
"CreateForWindow failed for HWND=0x{Hwnd:X8} HRESULT=0x{HResult:X8}.",
target.WindowHandle,
comEx.HResult);
throw new CaptureException(CaptureError.TargetGone,
$"CreateForWindow failed for HWND 0x{target.WindowHandle:X} (HRESULT 0x{comEx.HResult:X8}).", comEx);
}
catch (Exception ex)
{
_logger.LogWarningAt(
ex,
"CreateForWindow threw for HWND=0x{Hwnd:X8}.",
target.WindowHandle);
throw new CaptureException(CaptureError.TargetGone,
$"CreateForWindow failed for HWND 0x{target.WindowHandle:X}.", ex);
}
if (item is null)
{
_logger.LogWarningAt("GraphicsCaptureItem was null for HWND=0x{Hwnd:X8}.", target.WindowHandle);
throw new CaptureException(CaptureError.TargetGone, "GraphicsCaptureItem was null.");
}
@@ -100,6 +117,12 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
session.IsBorderRequired = false;
session.IsCursorCaptureEnabled = false;
_logger.LogInformationAt(
"WGC session started for HWND=0x{Hwnd:X8} size={Width}x{Height}.",
target.WindowHandle,
item.Size.Width,
item.Size.Height);
var tcs = new TaskCompletionSource<Direct3D11CaptureFrame>(
TaskCreationOptions.RunContinuationsAsynchronously);
@@ -129,11 +152,16 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
if (completed != tcs.Task)
{
cancellationToken.ThrowIfCancellationRequested();
_logger.LogWarningAt(
"WGC frame timeout after {Seconds:F1}s for HWND=0x{Hwnd:X8}.",
FrameTimeout.TotalSeconds,
target.WindowHandle);
throw new CaptureException(
CaptureError.NoFrameArrived,
$"No frame arrived within {FrameTimeout.TotalSeconds:F1}s.");
}
frame = await tcs.Task.ConfigureAwait(false);
_logger.LogDebugAt("WGC first frame received for HWND=0x{Hwnd:X8}.", target.WindowHandle);
}
finally
{
@@ -157,15 +185,26 @@ public sealed class WindowsGraphicsCaptureEngine : ICaptureEngine
{
throw new CaptureException(CaptureError.Cancelled, "Capture was cancelled.");
}
catch (COMException comEx)
{
_logger.LogErrorAt(
comEx,
"WGC capture COM failure for HWND=0x{Hwnd:X8} HRESULT=0x{HResult:X8}.",
target.WindowHandle,
comEx.HResult);
throw new CaptureException(CaptureError.Unknown,
$"WGC capture failed (HRESULT 0x{comEx.HResult:X8}): {comEx.Message}", comEx);
}
catch (Exception ex)
{
_logger.LogError(ex, "WGC capture failed for HWND 0x{Hwnd:X}.", target.WindowHandle);
_logger.LogErrorAt(ex, "WGC capture failed for HWND=0x{Hwnd:X8}.", target.WindowHandle);
throw new CaptureException(CaptureError.Unknown, "WGC capture failed: " + ex.Message, ex);
}
finally
{
session?.Dispose();
framePool?.Dispose();
_logger.LogDebugAt("WGC session disposed for HWND=0x{Hwnd:X8}.", target.WindowHandle);
// Note: `item` and `winrtDevice` are WinRT projections — they release automatically
// when the RCW is collected. Explicit dispose is optional but not required here.
}
@@ -53,11 +53,30 @@ public sealed partial class HotkeyConflictSniffer : IHotkeyConflictSniffer
var err = Marshal.GetLastWin32Error();
_logger.LogDebug(
"RegisterHotKey sniff failed for {Binding} (win32 error {Err}); treating as conflicted.",
binding, err);
"RegisterHotKey sniff failed for {Binding}; treating as conflicted. ({ErrCode}: {ErrText})",
binding,
err,
DescribeWin32Error(err));
return true;
}
/// <summary>
/// Map the handful of Win32 errors <c>RegisterHotKey</c> can realistically produce back
/// to human-readable names. Unknown codes fall through to <c>"UNKNOWN"</c> — the
/// numeric value is always logged alongside so diagnosis isn't blocked on the map
/// having complete coverage.
/// </summary>
private static string DescribeWin32Error(int code) => code switch
{
0 => "ERROR_SUCCESS",
5 => "ERROR_ACCESS_DENIED",
87 => "ERROR_INVALID_PARAMETER",
1400 => "ERROR_INVALID_WINDOW_HANDLE",
1409 => "ERROR_HOTKEY_ALREADY_REGISTERED",
1419 => "ERROR_HOTKEY_NOT_REGISTERED",
_ => "UNKNOWN",
};
[LibraryImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
@@ -59,7 +59,14 @@ public sealed class SharpHookHotkeyService : IHotkeyService
_binding = null;
if (_hook is not null)
{
try { _hook.Dispose(); } catch { /* ignore */ }
try
{
_hook.Dispose();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to dispose SharpHook on Stop.");
}
_hook = null;
_logger.LogInformation("Hotkey service stopped.");
}
@@ -72,7 +79,14 @@ public sealed class SharpHookHotkeyService : IHotkeyService
{
if (_disposed) return;
_disposed = true;
try { _hook?.Dispose(); } catch { /* ignore */ }
try
{
_hook?.Dispose();
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to dispose SharpHook on Dispose.");
}
_hook = null;
}
}
@@ -84,6 +98,7 @@ public sealed class SharpHookHotkeyService : IHotkeyService
_hook = new TaskPoolGlobalHook();
_hook.KeyPressed += OnKeyPressed;
_hook.RunAsync();
_logger.LogInformation("SharpHook TaskPoolGlobalHook started.");
}
private void OnKeyPressed(object? sender, KeyboardHookEventArgs e)
@@ -0,0 +1,34 @@
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.Infrastructure.Logging;
/// <summary>
/// Serilog <see cref="ILogEventEnricher"/> that fills empty defaults for the caller-info
/// properties (<c>File</c>, <c>Line</c>, <c>Member</c>) on every log event where the call
/// site didn't populate them via <c>CallerAwareLoggerExtensions</c>.
/// </summary>
/// <remarks>
/// Without this, the rolling-file output template <c>({File}:{Line})</c> would render as
/// the literal <c>({File}:{Line})</c> tokens on legacy call sites. With it, those call
/// sites produce <c>(:)</c> — ugly but honest ("no caller context here"), and visually
/// easy to filter out when grepping a log.
/// </remarks>
public sealed class CallerPropertyDefaultsEnricher : ILogEventEnricher
{
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
if (!logEvent.Properties.ContainsKey("File"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("File", string.Empty));
}
if (!logEvent.Properties.ContainsKey("Line"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Line", 0));
}
if (!logEvent.Properties.ContainsKey("Member"))
{
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("Member", string.Empty));
}
}
}
@@ -93,7 +93,36 @@ public sealed class InMemorySink : ILogEventSink, ILogBufferSource
Level: MapLevel(ev.Level),
SourceContext: sourceContext ?? string.Empty,
Message: writer.ToString(),
Exception: ev.Exception?.ToString());
Exception: ev.Exception?.ToString())
{
// Caller-info is injected by CallerAwareLoggerExtensions via MEL scope; absent
// on legacy call sites that still use Log.X or bare ILogger.LogInformation.
File = ReadStringProperty(ev, "File"),
Line = ReadInt32Property(ev, "Line"),
Member = ReadStringProperty(ev, "Member"),
};
}
private static string? ReadStringProperty(LogEvent ev, string name)
{
if (ev.Properties.TryGetValue(name, out var value) &&
value is ScalarValue { Value: string s } &&
!string.IsNullOrEmpty(s))
{
return s;
}
return null;
}
private static int? ReadInt32Property(LogEvent ev, string name)
{
if (ev.Properties.TryGetValue(name, out var value) &&
value is ScalarValue { Value: int i } &&
i > 0)
{
return i;
}
return null;
}
private static LogLevel MapLevel(LogEventLevel level) => level switch
@@ -0,0 +1,43 @@
using CaptureImage.Core.Abstractions;
using Serilog.Core;
using Serilog.Events;
namespace CaptureImage.Infrastructure.Logging;
/// <summary>
/// <see cref="ILogLevelSwitcher"/> backed by Serilog's <see cref="LoggingLevelSwitch"/>.
/// </summary>
public sealed class SerilogLogLevelSwitcher : ILogLevelSwitcher
{
private readonly LoggingLevelSwitch _levelSwitch;
public SerilogLogLevelSwitcher(LoggingLevelSwitch levelSwitch)
{
_levelSwitch = levelSwitch;
}
public string CurrentLevel => _levelSwitch.MinimumLevel switch
{
LogEventLevel.Verbose => "Debug",
LogEventLevel.Debug => "Debug",
LogEventLevel.Information => "Information",
LogEventLevel.Warning => "Warning",
LogEventLevel.Error => "Error",
LogEventLevel.Fatal => "Error",
_ => "Information",
};
public void SetLevel(string level)
{
_levelSwitch.MinimumLevel = level?.Trim().ToLowerInvariant() switch
{
"debug" => LogEventLevel.Debug,
"information" => LogEventLevel.Information,
"info" => LogEventLevel.Information,
"warning" => LogEventLevel.Warning,
"warn" => LogEventLevel.Warning,
"error" => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
}
}
@@ -108,8 +108,10 @@ public sealed class WmiProcessWatcher : IProcessWatcher
private void DisposeWatchers_NoLock()
{
try { _startWatcher?.Stop(); } catch { /* ignore */ }
try { _stopWatcher?.Stop(); } catch { /* ignore */ }
try { _startWatcher?.Stop(); }
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI creation watcher during teardown."); }
try { _stopWatcher?.Stop(); }
catch (Exception ex) { _logger.LogDebug(ex, "Failed to stop WMI deletion watcher during teardown."); }
_startWatcher?.Dispose();
_stopWatcher?.Dispose();
_startWatcher = null;
@@ -18,7 +18,7 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
private static readonly TimeSpan WriteDebounce = TimeSpan.FromMilliseconds(300);
/// <summary>Highest schema version this binary understands.</summary>
private const int SupportedVersion = 1;
private const int SupportedVersion = 2;
private readonly IFileSystem _fs;
private readonly ILogger<JsonSettingsStore> _logger;
@@ -91,6 +91,35 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
}
else
{
// v1 → v2 migration: earlier builds only tracked fields up to UI.
// System.Text.Json's source-gen deserializer leaves absent init-only
// strings at null instead of the record's init default, so explicitly
// set LogLevel here; then stamp Version=2 and trigger a write-back
// so the canonical on-disk form matches the current schema.
if (parsed.Version < SupportedVersion)
{
_logger.LogInformation(
"Migrating settings file {Path} from version {From} to {To}.",
_filePath, parsed.Version, SupportedVersion);
parsed = parsed with
{
Version = SupportedVersion,
LogLevel = string.IsNullOrWhiteSpace(parsed.LogLevel)
? "Information"
: parsed.LogLevel,
};
needsWriteBack = true;
}
// Defensive: even a v2-stamped file can arrive with LogLevel=null if it
// was hand-edited or produced by an older preview binary. Fill in the
// default so downstream code never sees null.
if (string.IsNullOrWhiteSpace(parsed.LogLevel))
{
parsed = parsed with { LogLevel = "Information" };
needsWriteBack = true;
}
loaded = parsed;
// Partial/missing/extra fields — re-serializing fills init defaults, so
// if the canonical form differs from the raw JSON, write back to
@@ -103,7 +132,8 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
needsWriteBack = true;
}
_logger.LogInformation(
"Settings loaded from {Path} (version {Version}).", _filePath, loaded.Version);
"Settings loaded from {Path} (version {Version}, log level {LogLevel}).",
_filePath, loaded.Version, loaded.LogLevel);
}
}
}
@@ -269,21 +299,37 @@ public sealed class JsonSettingsStore : ISettingsStore, IDisposable
private void TryDelete(string path)
{
try { if (_fs.File.Exists(path)) _fs.File.Delete(path); }
catch { /* best-effort */ }
try
{
if (_fs.File.Exists(path)) _fs.File.Delete(path);
}
catch (Exception ex)
{
// Best-effort cleanup — if the temp file can't be removed, a subsequent write
// will overwrite it via the rename-into-place path. Log at Debug so we can still
// correlate if it compounds into a real failure later.
_logger.LogDebug(ex, "Failed to delete {Path}.", path);
}
}
private static string Serialize(AppSettings settings) =>
JsonSerializer.Serialize(settings, SettingsJsonContext.Default.AppSettings);
private static AppSettings? Deserialize(string json)
private AppSettings? Deserialize(string json)
{
try
{
return JsonSerializer.Deserialize(json, SettingsJsonContext.Default.AppSettings);
}
catch (JsonException)
catch (JsonException ex)
{
// The caller turns a null return into "replace with defaults". Surface the root
// cause here so the log explains why, not just that parsing failed.
_logger.LogWarning(
ex,
"Malformed settings JSON ({LineNumber}:{BytePositionInLine}); reverting to defaults.",
ex.LineNumber,
ex.BytePositionInLine);
return null;
}
}
@@ -144,12 +144,28 @@ public sealed class VelopackUpdateService : IUpdateService
{
if (_manager is null || _pendingUpdate is null)
{
_logger.LogWarning(
"ApplyAndRestart invoked with no pending update (manager={HasManager}, pending={HasPending}).",
_manager is not null,
_pendingUpdate is not null);
throw new InvalidOperationException(
"No pending update to install. Call CheckAsync + DownloadAsync first.");
}
_logger.LogInformation(
"Applying update {Version} and restarting.",
_pendingUpdate.TargetFullRelease.Version);
EmitLog("Applying update and restarting…");
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
try
{
_manager.ApplyUpdatesAndRestart(_pendingUpdate.TargetFullRelease);
}
catch (Exception ex)
{
_logger.LogError(ex, "ApplyUpdatesAndRestart failed.");
EmitLog($"Apply failed: {ex.Message}");
throw;
}
}
private void EmitLog(string line)
@@ -1,7 +1,9 @@
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using CaptureImage.Core.Abstractions;
using Microsoft.Extensions.Logging;
namespace CaptureImage.UI.Localization;
@@ -22,12 +24,22 @@ public sealed class ResxLocalizationService : ILocalizationService
};
private readonly ResourceManager _resourceManager;
private readonly ILogger<ResxLocalizationService> _logger;
/// <summary>
/// Tracks <c>(culture, key)</c> pairs we've already logged a "missing string" warning for.
/// Missing keys are usually the same handful repeated on every refresh; logging once per
/// pair per process keeps the signal without flooding the rolling file.
/// </summary>
private readonly ConcurrentDictionary<string, byte> _loggedMissingKeys = new();
private CultureInfo _currentCulture;
public ResxLocalizationService()
public ResxLocalizationService(ILogger<ResxLocalizationService> logger)
{
_resourceManager = new ResourceManager(ResourceBaseName, typeof(ResxLocalizationService).Assembly);
_currentCulture = CultureInfo.GetCultureInfo("en-US");
_logger = logger;
}
public event PropertyChangedEventHandler? PropertyChanged;
@@ -51,15 +63,42 @@ public sealed class ResxLocalizationService : ILocalizationService
if (string.IsNullOrEmpty(key)) return string.Empty;
try
{
return _resourceManager.GetString(key, _currentCulture) ?? $"[{key}]";
var value = _resourceManager.GetString(key, _currentCulture);
if (value is null)
{
LogMissingKeyOnce(key);
return $"[{key}]";
}
return value;
}
catch
catch (Exception ex)
{
LogMissingKeyOnce(key, ex);
return $"[{key}]";
}
}
}
private void LogMissingKeyOnce(string key, Exception? exception = null)
{
var dedupKey = $"{_currentCulture.Name}|{key}";
if (!_loggedMissingKeys.TryAdd(dedupKey, 0)) return;
if (exception is null)
{
_logger.LogWarning(
"Localization key '{Key}' missing for culture {Culture}; falling back to bracketed key.",
key, _currentCulture.Name);
}
else
{
_logger.LogWarning(
exception,
"Localization lookup threw for key '{Key}' culture {Culture}; falling back to bracketed key.",
key, _currentCulture.Name);
}
}
public void SetCulture(CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(culture);
@@ -88,6 +88,9 @@
<data name="Settings_ImportTitle" xml:space="preserve"><value>استيراد الإعدادات</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>تصدير الإعدادات</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>فتح ملف الإعدادات</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>السجلات</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>الحد الأدنى لمستوى السجل</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>يُصفّي ملف السجل المتدوّر وعارض السجل. اختر Debug للتشخيص، Information للاستخدام اليومي، Warning أو Error لتقليل الضوضاء.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>تحديث</value></data>
@@ -131,6 +134,8 @@
<data name="Log_Clear" xml:space="preserve"><value>مسح</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} حدث</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>لا توجد أحداث سجل بعد. ستظهر الأحداث المباشرة من محرك الالتقاط هنا.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>الحد الأدنى:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>فتح المجلد</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>معاينة</value></data>
@@ -88,6 +88,9 @@
<data name="Settings_ImportTitle" xml:space="preserve"><value>Import settings</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>Export settings</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>Open settings file</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>Logging</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>Minimum log level</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Filters the rolling log file and viewer. Pick Debug for support diagnostics, Information for day-to-day, Warning or Error to keep logs quiet.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>Update</value></data>
@@ -131,6 +134,8 @@
<data name="Log_Clear" xml:space="preserve"><value>Clear</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} events</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>No log events yet. Live events from the capture engine will appear here.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>Min level:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>Open folder</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>Preview</value></data>
@@ -88,6 +88,9 @@
<data name="Settings_ImportTitle" xml:space="preserve"><value>Nhập cài đặt</value></data>
<data name="Settings_ExportTitle" xml:space="preserve"><value>Xuất cài đặt</value></data>
<data name="Settings_OpenFile" xml:space="preserve"><value>Mở tệp cài đặt</value></data>
<data name="Settings_Logging" xml:space="preserve"><value>Ghi log</value></data>
<data name="Settings_LogLevel" xml:space="preserve"><value>Mức log tối thiểu</value></data>
<data name="Settings_LogLevelHint" xml:space="preserve"><value>Lọc cả file log xoay vòng và cửa sổ Log. Chọn Debug khi gỡ lỗi, Information cho vận hành hằng ngày, Warning hoặc Error để giữ log gọn.</value></data>
<!-- Update -->
<data name="Update_Title" xml:space="preserve"><value>Cập nhật</value></data>
@@ -131,6 +134,8 @@
<data name="Log_Clear" xml:space="preserve"><value>Xoá</value></data>
<data name="Log_EventsCount" xml:space="preserve"><value>{0} sự kiện</value></data>
<data name="Log_EmptyState" xml:space="preserve"><value>Chưa có sự kiện nhật ký nào. Sự kiện thời gian thực từ capture engine sẽ xuất hiện ở đây.</value></data>
<data name="Log_Filter" xml:space="preserve"><value>Mức tối thiểu:</value></data>
<data name="Log_RevealFolder" xml:space="preserve"><value>Mở thư mục</value></data>
<!-- Preview -->
<data name="Preview_Title" xml:space="preserve"><value>Xem trước</value></data>
@@ -42,7 +42,7 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
_trayIcon = new TrayIcon
{
Icon = BuildRuntimeIcon(),
Icon = BuildRuntimeIconSafely(),
ToolTipText = "CaptureImage",
IsVisible = true,
Menu = BuildMenu(),
@@ -56,7 +56,23 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
_mainWindow.Closing += OnMainWindowClosing;
_localization.PropertyChanged += OnLocalizationChanged;
_logger.LogInformation("Tray icon initialized.");
_logger.LogInformation("Tray icon initialized and visible.");
}
private WindowIcon? BuildRuntimeIconSafely()
{
try
{
return BuildRuntimeIcon();
}
catch (Exception ex)
{
// A SkiaSharp / native-asset failure here used to take the whole startup down.
// Fall back to a null icon (Avalonia renders a default glyph) and log — the
// user still gets a tray entry, just one without our branding.
_logger.LogWarning(ex, "Failed to render runtime tray icon via SkiaSharp; falling back to default.");
return null;
}
}
private void OnLocalizationChanged(object? sender, PropertyChangedEventArgs e)
@@ -85,6 +101,7 @@ public sealed class AvaloniaTrayIconHost : ITrayIconHost
_trayIcon.Dispose();
_trayIcon = null;
}
_logger.LogInformation("Tray icon disposed.");
}
// -- menu ----------------------------------------------------------------
+5 -1
View File
@@ -7,7 +7,11 @@
x:Class="CaptureImage.UI.Views.AboutView"
x:DataType="vm:AboutViewModel">
<ScrollViewer>
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16,24,24" Spacing="18" MaxWidth="640">
<!-- Header -->
+29 -5
View File
@@ -16,21 +16,37 @@
<Grid RowDefinitions="Auto,*">
<!-- Header + controls -->
<Grid Grid.Row="0" ColumnDefinitions="*,Auto,Auto,Auto" Margin="0,0,0,8">
<Grid Grid.Row="0"
ColumnDefinitions="*,Auto,Auto,Auto,Auto,Auto,Auto"
Margin="0,0,0,8">
<TextBlock Grid.Column="0"
Text="{Binding Localization[Log_Title]}"
FontSize="14"
FontWeight="SemiBold"
VerticalAlignment="Center" />
<Button Grid.Column="1"
<TextBlock Grid.Column="1"
Text="{Binding FilterLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center"
Margin="0,0,6,0" />
<ComboBox Grid.Column="2"
ItemsSource="{Binding FilterLevels}"
SelectedItem="{Binding SelectedFilterLevel, Mode=TwoWay}"
MinWidth="110"
Margin="0,0,8,0" />
<Button Grid.Column="3"
Command="{Binding TogglePauseCommand}"
Content="{Binding TogglePauseLabel}"
Margin="0,0,8,0" />
<Button Grid.Column="2"
<Button Grid.Column="4"
Command="{Binding ClearCommand}"
Content="{Binding Localization[Log_Clear]}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
<Button Grid.Column="5"
Command="{Binding RevealLogsFolderCommand}"
Content="{Binding RevealFolderLabel}"
Margin="0,0,8,0" />
<TextBlock Grid.Column="6"
Text="{Binding EventsCountText}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
VerticalAlignment="Center" />
@@ -44,7 +60,7 @@
<ItemsControl ItemsSource="{Binding Entries}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="models:LogEntry">
<Grid ColumnDefinitions="Auto,Auto,*" Margin="0,1">
<Grid ColumnDefinitions="Auto,Auto,Auto,*" Margin="0,1">
<TextBlock Grid.Column="0"
Text="{Binding Timestamp, StringFormat='HH:mm:ss.fff'}"
FontFamily="Consolas, Courier New, monospace"
@@ -58,6 +74,14 @@
Width="45"
Margin="0,0,8,0" />
<TextBlock Grid.Column="2"
Text="{Binding FileLineText}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
Width="170"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
TextTrimming="CharacterEllipsis"
Margin="0,0,8,0" />
<TextBlock Grid.Column="3"
Text="{Binding Message}"
FontFamily="Consolas, Courier New, monospace"
FontSize="11"
+28 -6
View File
@@ -15,9 +15,9 @@
x:Class="CaptureImage.UI.Views.MainWindow"
x:DataType="vm:MainWindowViewModel"
Title="CaptureImage"
Width="960" Height="600"
MinWidth="960" MinHeight="600"
MaxWidth="960" MaxHeight="600"
Width="1200" Height="720"
MinWidth="1200" MinHeight="720"
MaxWidth="1200" MaxHeight="720"
CanResize="False"
WindowStartupLocation="CenterScreen"
FlowDirection="{Binding Localization.CurrentFlowDirection, Converter={x:Static conv:FlowDirectionConverter.Instance}}">
@@ -108,11 +108,33 @@
</Grid>
<!-- Log viewer drawer — overlays the right 400px when toggled. -->
<views:LogViewerView Width="400"
<!-- Log viewer drawer — overlays the right 480px of the content grid with a
200ms slide-in + fade. Always kept in the visual tree so the transitions
fire on every toggle; IsHitTestVisible + Classes.visible let us collapse
interaction + drive the animation state from IsLogViewerVisible. -->
<views:LogViewerView x:Name="LogDrawer"
Width="480"
HorizontalAlignment="Right"
DataContext="{Binding LogViewer}"
IsVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}" />
Classes.visible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}"
IsHitTestVisible="{Binding $parent[Window].((vm:MainWindowViewModel)DataContext).IsLogViewerVisible}">
<views:LogViewerView.Styles>
<Style Selector="views|LogViewerView">
<Setter Property="Opacity" Value="0" />
<Setter Property="RenderTransform" Value="translateX(48px)" />
<Setter Property="Transitions">
<Transitions>
<DoubleTransition Property="Opacity" Duration="0:0:0.18" Easing="CircularEaseOut" />
<TransformOperationsTransition Property="RenderTransform" Duration="0:0:0.22" Easing="CircularEaseOut" />
</Transitions>
</Setter>
</Style>
<Style Selector="views|LogViewerView.visible">
<Setter Property="Opacity" Value="1" />
<Setter Property="RenderTransform" Value="translateX(0)" />
</Style>
</views:LogViewerView.Styles>
</views:LogViewerView>
<!-- Toast overlay — anchored bottom-right, floats over the content grid.
Under RTL FlowDirection Avalonia automatically mirrors Right/Left edges,
+24 -1
View File
@@ -9,7 +9,11 @@
x:Class="CaptureImage.UI.Views.SettingsView"
x:DataType="vm:SettingsViewModel">
<ScrollViewer>
<!-- HorizontalScrollBarVisibility=Disabled prevents the horizontal bar from ever
appearing; Vertical=Hidden lets mouse-wheel scrolling keep working but hides
the track so the view reads cleanly on a fixed window. -->
<ScrollViewer HorizontalScrollBarVisibility="Disabled"
VerticalScrollBarVisibility="Hidden">
<StackPanel Margin="24,16" Spacing="18" MaxWidth="620">
<TextBlock Text="{Binding TitleLabel}" FontSize="22" FontWeight="SemiBold" />
@@ -89,6 +93,25 @@
IsChecked="{Binding SoundEnabled, Mode=TwoWay}" />
</StackPanel>
<!-- Logging -->
<StackPanel Spacing="6">
<TextBlock Text="{Binding LoggingLabel}"
FontSize="13"
FontWeight="SemiBold" />
<StackPanel Spacing="4">
<TextBlock Text="{Binding LogLevelLabel}"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}"
FontSize="12" />
<ComboBox ItemsSource="{Binding SupportedLogLevels}"
SelectedItem="{Binding SelectedLogLevel, Mode=TwoWay}"
HorizontalAlignment="Stretch" />
<TextBlock Text="{Binding LogLevelHint}"
FontSize="11"
TextWrapping="Wrap"
Foreground="{DynamicResource SystemControlForegroundBaseMediumBrush}" />
</StackPanel>
</StackPanel>
<!-- Import / export / open -->
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Name="ImportButton" Content="{Binding ImportLabel}" />
@@ -1,19 +1,27 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Logging;
using CaptureImage.Core.Models;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging;
// Disambiguate — `LogLevel` here means the one in LogEntry (Serilog-derived severity),
// not MEL's `Microsoft.Extensions.Logging.LogLevel` used by the `_logger` field.
using LogLevel = CaptureImage.Core.Models.LogLevel;
namespace CaptureImage.ViewModels.Logs;
/// <summary>
/// Live log viewer for the drawer pane. Hydrates from the ring buffer on first show,
/// appends new entries as they fire, and supports pause/resume/clear/export.
/// appends new entries as they fire, and supports pause/resume/clear/export plus a
/// view-side level filter and a button to open the rolling-file folder in Explorer.
/// </summary>
public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
{
@@ -23,6 +31,8 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
private readonly ILogBufferSource _source;
private readonly IUIThreadDispatcher _dispatcher;
private readonly ILogger<LogViewerViewModel> _logger;
private readonly IToastService _toasts;
private bool _hydrated;
private bool _disposed;
@@ -30,20 +40,42 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
public ObservableCollection<LogEntry> Entries { get; } = new();
/// <summary>Options shown in the level-filter dropdown. Order matters: lowest to highest.</summary>
public IReadOnlyList<LogLevel> FilterLevels { get; } = new[]
{
LogLevel.Verbose,
LogLevel.Debug,
LogLevel.Information,
LogLevel.Warning,
LogLevel.Error,
};
[ObservableProperty]
private bool _isPaused;
[ObservableProperty]
private bool _isVisible;
/// <summary>
/// Minimum level the viewer displays. Entries below this get hidden from
/// <see cref="Entries"/> but still live in the sink buffer, so Export always carries
/// the full history regardless of this filter.
/// </summary>
[ObservableProperty]
private LogLevel _selectedFilterLevel = LogLevel.Verbose;
public LogViewerViewModel(
ILogBufferSource source,
IUIThreadDispatcher dispatcher,
ILocalizationService localization)
ILocalizationService localization,
ILogger<LogViewerViewModel> logger,
IToastService toasts)
{
_source = source;
_dispatcher = dispatcher;
Localization = localization;
_logger = logger;
_toasts = toasts;
_source.Emitted += OnEmitted;
Localization.PropertyChanged += OnLocalizationChanged;
@@ -63,6 +95,8 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(TogglePauseLabel));
OnPropertyChanged(nameof(EventsCountText));
OnPropertyChanged(nameof(EmptyStateText));
OnPropertyChanged(nameof(FilterLabel));
OnPropertyChanged(nameof(RevealFolderLabel));
// Refresh the `{Binding Localization[Log_Title]}` / `[Log_Clear]` direct
// indexer bindings in the header. v1.1.1 hotfix — the service's own
// Item[] notification alone doesn't reliably re-resolve the path.
@@ -92,6 +126,12 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
/// <summary>Localized hint shown inside the drawer when no log events have fired yet.</summary>
public string EmptyStateText => Localization["Log_EmptyState"];
/// <summary>Localized label for the minimum-level filter dropdown.</summary>
public string FilterLabel => Localization["Log_Filter"];
/// <summary>Localized button label that opens the rolling-file folder in Explorer.</summary>
public string RevealFolderLabel => Localization["Log_RevealFolder"];
public bool HasNoEntries => Entries.Count == 0;
partial void OnIsPausedChanged(bool value)
@@ -100,6 +140,24 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(TogglePauseLabel));
}
partial void OnSelectedFilterLevelChanged(LogLevel value)
{
// Rebuild the visible list from the sink snapshot whenever the filter moves.
// O(2000) — trivial and only runs on user input.
Entries.Clear();
var snapshot = _source.Snapshot();
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
private bool PassesFilter(LogEntry entry) => entry.Level >= SelectedFilterLevel;
/// <summary>
/// Called the first time the drawer is shown. Fills the ObservableCollection from the
/// sink's snapshot so the user sees historical log events too.
@@ -112,7 +170,10 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
var start = Math.Max(0, snapshot.Count - MaxVisibleEntries);
for (var i = start; i < snapshot.Count; i++)
{
Entries.Add(snapshot[i]);
if (PassesFilter(snapshot[i]))
{
Entries.Add(snapshot[i]);
}
}
}
@@ -126,6 +187,21 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
[RelayCommand]
private void TogglePause() => IsPaused = !IsPaused;
[RelayCommand]
private void RevealLogsFolder()
{
var folder = LogPaths.GetLogsDirectory();
try
{
Process.Start(new ProcessStartInfo(folder) { UseShellExecute = true });
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to open logs folder {Path}.", folder);
_toasts.ShowError(Localization["Toast_Error"], ex.Message);
}
}
[RelayCommand]
private async Task ExportAsync(string filePath)
{
@@ -137,6 +213,11 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
{
sb.Append('[').Append(entry.Timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff"));
sb.Append(' ').Append(entry.Level.ToString().ToUpperInvariant().Substring(0, 3)).Append("] ");
var fileLine = entry.FileLineText;
if (!string.IsNullOrEmpty(fileLine))
{
sb.Append('(').Append(fileLine).Append(") ");
}
if (!string.IsNullOrEmpty(entry.SourceContext))
{
sb.Append(entry.SourceContext).Append(": ");
@@ -155,6 +236,7 @@ public sealed partial class LogViewerViewModel : ViewModelBase, IDisposable
// Marshal to UI thread before mutating the ObservableCollection.
_dispatcher.Post(() =>
{
if (!PassesFilter(entry)) return;
Entries.Add(entry);
while (Entries.Count > MaxVisibleEntries)
{
@@ -21,6 +21,7 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
private readonly ISettingsStore _settings;
private readonly IToastService _toasts;
private readonly ILogger<SettingsViewModel> _logger;
private readonly ILogLevelSwitcher _logLevelSwitcher;
private bool _suppressPush;
private bool _disposed;
@@ -34,6 +35,14 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public ObservableCollection<ImageFormat> SupportedFormats { get; } =
new(new[] { ImageFormat.Png, ImageFormat.Jpeg, ImageFormat.Webp, ImageFormat.Tiff });
/// <summary>
/// Log-level options shown in the Settings Logging picker. Order matches user
/// expectation (most-verbose first) and the strings match <see cref="AppSettings.LogLevel"/>
/// so the picker can bind directly to <see cref="SelectedLogLevel"/>.
/// </summary>
public ObservableCollection<string> SupportedLogLevels { get; } =
new(new[] { "Debug", "Information", "Warning", "Error" });
[ObservableProperty]
private CultureInfo _selectedCulture;
@@ -61,6 +70,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
[ObservableProperty]
private bool _soundEnabled;
[ObservableProperty]
private string _selectedLogLevel = "Information";
public string SettingsFilePath => _settings.SettingsFilePath;
// -- localized labels ---------------------------------------------------
@@ -91,17 +103,22 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
public string ImportLabel => Localization["Settings_Import"];
public string ExportLabel => Localization["Settings_Export"];
public string OpenFileLabel => Localization["Settings_OpenFile"];
public string LoggingLabel => Localization["Settings_Logging"];
public string LogLevelLabel => Localization["Settings_LogLevel"];
public string LogLevelHint => Localization["Settings_LogLevelHint"];
public SettingsViewModel(
ISettingsStore settings,
ILocalizationService localization,
IToastService toasts,
HotkeyBindingViewModel hotkey,
ILogger<SettingsViewModel> logger)
ILogger<SettingsViewModel> logger,
ILogLevelSwitcher logLevelSwitcher)
{
_settings = settings;
_toasts = toasts;
_logger = logger;
_logLevelSwitcher = logLevelSwitcher;
Localization = localization;
Hotkey = hotkey;
@@ -152,6 +169,9 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
OnPropertyChanged(nameof(ImportLabel));
OnPropertyChanged(nameof(ExportLabel));
OnPropertyChanged(nameof(OpenFileLabel));
OnPropertyChanged(nameof(LoggingLabel));
OnPropertyChanged(nameof(LogLevelLabel));
OnPropertyChanged(nameof(LogLevelHint));
}
}
@@ -190,6 +210,11 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
PreviewBeforeSave = current.Capture.PreviewBeforeSave;
MinimizeToTray = current.UI.MinimizeToTray;
SoundEnabled = current.UI.SoundEnabled;
// Fall back to the first supported value if the persisted string doesn't match —
// that can happen after a hand-edit or a downgrade from a future schema.
SelectedLogLevel = SupportedLogLevels.Contains(current.LogLevel)
? current.LogLevel
: SupportedLogLevels[1]; // Information
}
finally
{
@@ -252,6 +277,16 @@ public sealed partial class SettingsViewModel : ViewModelBase, IDisposable
_settings.Update(s => s with { UI = s.UI with { SoundEnabled = value } });
}
partial void OnSelectedLogLevelChanged(string value)
{
if (_suppressPush || string.IsNullOrWhiteSpace(value)) return;
_settings.Update(s => s with { LogLevel = value });
// Flip the live Serilog minimum level immediately — no restart needed. The
// persisted value syncs via the debounced settings writer.
_logLevelSwitcher.SetLevel(value);
_logger.LogInformation("Log level changed to {Level}.", value);
}
private static int Clamp(int v) => v < 1 ? 1 : v > 100 ? 100 : v;
[RelayCommand]
@@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.IO;
using CaptureImage.Core.Logging;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Xunit;
namespace CaptureImage.Core.Tests.Logging;
/// <summary>
/// Validates that <c>LogXAt</c> extensions attach <c>File</c> / <c>Line</c> / <c>Member</c>
/// as MEL scope state — which Serilog's MEL bridge then surfaces as structured
/// <see cref="Serilog.Events.LogEvent"/> properties at runtime.
/// </summary>
/// <remarks>
/// Rather than stand up the real Serilog pipeline, we use a tiny spy <see cref="ILogger"/>
/// that captures whatever scope state arrives. That's enough to assert the extensions
/// pass the caller context through correctly; the end-to-end "scope reaches the rolling
/// file" behaviour is covered by manual verification.
/// </remarks>
public class CallerAwareLoggerExtensionsTests
{
[Fact]
public void LogInformationAt_InjectsCallerContextIntoScope()
{
var spy = new ScopeCapturingLogger();
spy.LogInformationAt("hello");
var captured = spy.Scopes.Should().ContainSingle().Subject;
captured.Should().ContainKey("Member");
captured.Should().ContainKey("File");
captured.Should().ContainKey("Line");
captured["Member"].Should().Be(nameof(LogInformationAt_InjectsCallerContextIntoScope));
captured["File"].Should().Be("CallerAwareLoggerExtensionsTests.cs");
((int)captured["Line"]!).Should().BeGreaterThan(0);
}
[Fact]
public void LogWarningAt_WithException_ForwardsExceptionAndCaller()
{
var spy = new ScopeCapturingLogger();
var ex = new InvalidOperationException("boom");
spy.LogWarningAt(ex, "with exception");
spy.Entries.Should().ContainSingle()
.Which.Exception.Should().Be(ex);
spy.Scopes.Should().ContainSingle()
.Which.Should().ContainKey("File").WhoseValue
.Should().Be("CallerAwareLoggerExtensionsTests.cs");
}
[Fact]
public void LogErrorAt_WithTwoArgs_PassesArgsThroughToLogger()
{
var spy = new ScopeCapturingLogger();
var ex = new IOException("disk full");
spy.LogErrorAt(ex, "failed to save {Path} size={Size}", "/tmp/x", 1024);
spy.Entries.Should().ContainSingle()
.Which.State!.ToString().Should().Contain("/tmp/x").And.Contain("1024");
}
[Fact]
public void CallerScope_StripsBuildMachineAbsolutePath()
{
// Simulate [CallerFilePath] having produced an absolute path — the helper must
// strip the directory portion so we don't leak E:\build-agent\... into the log.
var spy = new ScopeCapturingLogger();
spy.LogInformationAt(
"probe",
member: "test",
filePath: @"C:\build\machine\deep\path\Module.cs",
line: 7);
var scope = spy.Scopes.Should().ContainSingle().Subject;
scope["File"].Should().Be("Module.cs");
}
// -- helpers --------------------------------------------------------------
/// <summary>Minimal spy capturing every Log call + its surrounding scope state.</summary>
private sealed class ScopeCapturingLogger : ILogger
{
public List<Dictionary<string, object?>> Scopes { get; } = new();
public List<(LogLevel Level, Exception? Exception, object? State)> Entries { get; } = new();
private readonly Stack<Dictionary<string, object?>> _currentScopes = new();
public IDisposable BeginScope<TState>(TState state) where TState : notnull
{
var dict = new Dictionary<string, object?>();
if (state is IEnumerable<KeyValuePair<string, object>> pairs)
{
foreach (var kvp in pairs)
{
dict[kvp.Key] = kvp.Value;
}
}
Scopes.Add(dict);
_currentScopes.Push(dict);
return new ScopeToken(this);
}
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter)
{
Entries.Add((logLevel, exception, state));
}
private sealed class ScopeToken : IDisposable
{
private readonly ScopeCapturingLogger _owner;
public ScopeToken(ScopeCapturingLogger owner) => _owner = owner;
public void Dispose()
{
if (_owner._currentScopes.Count > 0) _owner._currentScopes.Pop();
}
}
}
}
@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using CaptureImage.Core.Models;
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Events;
using Serilog.Parsing;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Covers the ring-buffer semantics, pause/resume behaviour, and <c>Snapshot()</c> copy
/// guarantees of <see cref="InMemorySink"/> — the real-time log viewer's event source.
/// </summary>
public class InMemorySinkTests
{
[Fact]
public void Emit_AppendsToBuffer_AndRaisesEmitted_WhenNotPaused()
{
var sink = new InMemorySink();
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hello", LogEventLevel.Information));
sink.Snapshot().Should().HaveCount(1);
sink.Snapshot()[0].Message.Should().Be("hello");
raised.Should().HaveCount(1);
raised[0].Level.Should().Be(LogLevel.Information);
}
[Fact]
public void Emit_WhilePaused_StillBuffersButDoesNotRaiseEmitted()
{
var sink = new InMemorySink { Paused = true };
var raised = new List<LogEntry>();
sink.Emitted += (_, entry) => raised.Add(entry);
sink.Emit(Event("hidden", LogEventLevel.Warning));
sink.Snapshot().Should().HaveCount(1);
raised.Should().BeEmpty();
}
[Fact]
public void Emit_OverflowingCapacity_EvictsOldestFirst()
{
var sink = new InMemorySink();
// Fire one beyond capacity so the first event has to be dropped.
for (var i = 0; i < InMemorySink.MaxCapacity + 1; i++)
{
sink.Emit(Event($"msg-{i}", LogEventLevel.Information));
}
var snapshot = sink.Snapshot();
snapshot.Should().HaveCount(InMemorySink.MaxCapacity);
snapshot[0].Message.Should().Be("msg-1"); // index 0 evicted
snapshot[^1].Message.Should().Be($"msg-{InMemorySink.MaxCapacity}");
}
[Fact]
public void Snapshot_ReturnsCopy_MutationsDontAffectBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("a", LogEventLevel.Information));
var firstSnapshot = sink.Snapshot();
sink.Emit(Event("b", LogEventLevel.Information));
// The earlier snapshot is frozen at the moment it was taken.
firstSnapshot.Should().HaveCount(1);
firstSnapshot[0].Message.Should().Be("a");
// But the sink itself has moved on.
sink.Snapshot().Should().HaveCount(2);
}
[Fact]
public void Clear_EmptiesBuffer()
{
var sink = new InMemorySink();
sink.Emit(Event("x", LogEventLevel.Information));
sink.Emit(Event("y", LogEventLevel.Information));
sink.Clear();
sink.Snapshot().Should().BeEmpty();
}
[Fact]
public void Emit_CapturesCallerProperties_WhenPresentOnEvent()
{
var sink = new InMemorySink();
var ev = EventWithCaller("with caller", "Engine.cs", 42, "Start");
sink.Emit(ev);
var entry = sink.Snapshot()[0];
entry.File.Should().Be("Engine.cs");
entry.Line.Should().Be(42);
entry.Member.Should().Be("Start");
entry.FileLineText.Should().Be("Engine.cs:42");
}
[Fact]
public void Emit_LeavesCallerPropertiesNull_WhenAbsent()
{
var sink = new InMemorySink();
sink.Emit(Event("plain", LogEventLevel.Information));
var entry = sink.Snapshot()[0];
entry.File.Should().BeNull();
entry.Line.Should().BeNull();
entry.Member.Should().BeNull();
entry.FileLineText.Should().BeEmpty();
}
// -- helpers --------------------------------------------------------------
private static LogEvent Event(string message, LogEventLevel level)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
level,
exception: null,
template,
properties: Array.Empty<LogEventProperty>());
}
private static LogEvent EventWithCaller(string message, string file, int line, string member)
{
var template = new MessageTemplateParser().Parse(message);
return new LogEvent(
DateTimeOffset.UtcNow,
LogEventLevel.Information,
exception: null,
template,
properties: new[]
{
new LogEventProperty("File", new ScalarValue(file)),
new LogEventProperty("Line", new ScalarValue(line)),
new LogEventProperty("Member", new ScalarValue(member)),
});
}
}
@@ -0,0 +1,61 @@
using CaptureImage.Infrastructure.Logging;
using FluentAssertions;
using Serilog.Core;
using Serilog.Events;
using Xunit;
namespace CaptureImage.Infrastructure.Tests.Logging;
/// <summary>
/// Verifies the canonical mapping between <see cref="AppSettings.LogLevel"/> strings and
/// Serilog's <see cref="LogEventLevel"/>. Covers the alias forms (info/warn) and the
/// unknown-value fallback.
/// </summary>
public class SerilogLogLevelSwitcherTests
{
[Theory]
[InlineData("Debug", LogEventLevel.Debug)]
[InlineData("debug", LogEventLevel.Debug)]
[InlineData("Information", LogEventLevel.Information)]
[InlineData("info", LogEventLevel.Information)]
[InlineData("Warning", LogEventLevel.Warning)]
[InlineData("warn", LogEventLevel.Warning)]
[InlineData("Error", LogEventLevel.Error)]
[InlineData("ERROR", LogEventLevel.Error)]
public void SetLevel_CanonicalAndAliasNames_MapToSerilogLevel(string input, LogEventLevel expected)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input);
levelSwitch.MinimumLevel.Should().Be(expected);
}
[Theory]
[InlineData("")]
[InlineData("TRACE")]
[InlineData("Verbose")]
[InlineData(null)]
[InlineData("nonsense")]
public void SetLevel_UnknownOrNull_FallsBackToInformation(string? input)
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Verbose);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel(input!);
levelSwitch.MinimumLevel.Should().Be(LogEventLevel.Information);
}
[Fact]
public void CurrentLevel_ReportsCanonicalNameAfterSetLevel()
{
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information);
var switcher = new SerilogLogLevelSwitcher(levelSwitch);
switcher.SetLevel("debug");
switcher.CurrentLevel.Should().Be("Debug");
}
}
@@ -36,10 +36,11 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
store.Current.CaptureHotkey.Should().Be(HotkeyBinding.Default);
store.Current.Capture.DefaultFormat.Should().Be(ImageFormat.Png);
store.Current.LogLevel.Should().Be("Information");
}
[Fact]
@@ -136,7 +137,7 @@ public class JsonSettingsStoreTests
await store.LoadAsync();
store.Current.Version.Should().Be(1);
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("en-US");
}
@@ -154,6 +155,46 @@ public class JsonSettingsStoreTests
store.Current.Culture.Should().Be("en-US");
}
[Fact]
public async Task LoadAsync_V1File_MigratesToV2AndWritesBack()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
// Hand-crafted v1 document — no logLevel field present. System.Text.Json fills
// it with the init default (Information), and the migration path stamps Version=2
// + triggers a write-back so the on-disk file ends up canonical.
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 1, \"culture\": \"vi-VN\", \"theme\": \"System\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.Culture.Should().Be("vi-VN");
store.Current.LogLevel.Should().Be("Information");
// Write-back normalised the file — next parse sees v2 directly.
var written = fs.File.ReadAllText(ExpectedPath);
written.Should().Contain("\"version\": 2");
written.Should().Contain("\"logLevel\": \"Information\"");
}
[Fact]
public async Task LoadAsync_V2File_PreservesLogLevelField()
{
var (store, fs) = Build();
var appDataRoot = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var dir = Path.Combine(appDataRoot, "CaptureImage");
fs.Directory.CreateDirectory(dir);
fs.File.WriteAllText(ExpectedPath,
"{\"version\": 2, \"culture\": \"en-US\", \"logLevel\": \"Debug\"}");
await store.LoadAsync();
store.Current.Version.Should().Be(2);
store.Current.LogLevel.Should().Be("Debug");
}
[Fact]
public async Task ExportAsync_WritesCurrentSettings()
{
@@ -5,6 +5,7 @@ using System.Linq;
using CaptureImage.Core.Abstractions;
using CaptureImage.UI.Localization;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Xunit;
namespace CaptureImage.UI.Tests.Localization;
@@ -40,7 +41,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_Vietnamese_UpdatesCurrentCultureAndThreadCulture()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var vi = CultureInfo.GetCultureInfo("vi-VN");
svc.SetCulture(vi);
@@ -55,7 +56,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_Arabic_FlipsFlowDirectionToRightToLeft()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc.SetCulture(CultureInfo.GetCultureInfo("ar-SA"));
@@ -65,7 +66,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_English_FlowDirectionLeftToRight()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
// Default is en-US; switch elsewhere first so SetCulture actually fires.
svc.SetCulture(CultureInfo.GetCultureInfo("ar-SA"));
@@ -77,7 +78,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_RaisesItemIndexer_CurrentCulture_AndFlowDirection_Once_Each()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var names = new List<string?>();
svc.PropertyChanged += (_, e) => names.Add(e.PropertyName);
@@ -92,7 +93,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_AlsoRaisesCultureChangedEvent()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var cultureChanged = 0;
svc.CultureChanged += (_, _) => cultureChanged++;
@@ -104,7 +105,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_SameAsCurrent_IsNoOp()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
// Constructor seeds with en-US.
var events = 0;
svc.PropertyChanged += (_, _) => events++;
@@ -120,7 +121,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SetCulture_Null_Throws()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
Action act = () => svc.SetCulture(null!);
@@ -130,7 +131,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void Indexer_MissingKey_ReturnsKeyInBrackets()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var result = svc["NoSuchKey_DefinitelyMissing_1234"];
@@ -140,7 +141,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void Indexer_EmptyKey_ReturnsEmptyString()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc[""].Should().BeEmpty();
}
@@ -148,7 +149,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void Indexer_KnownKey_ReturnsEnglishByDefault()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc["Nav_Dashboard"].Should().Be("Dashboard");
}
@@ -156,7 +157,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void Indexer_AfterSetCulture_ReturnsLocalizedValue()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
svc.SetCulture(CultureInfo.GetCultureInfo("vi-VN"));
svc["Nav_Dashboard"].Should().Be("Bảng điều khiển");
@@ -165,7 +166,7 @@ public class ResxLocalizationServiceTests : IDisposable
[Fact]
public void SupportedCultures_IncludesShippedLanguages()
{
var svc = new ResxLocalizationService();
var svc = new ResxLocalizationService(NullLogger<ResxLocalizationService>.Instance);
var names = svc.SupportedCultures.Select(c => c.Name).ToArray();
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CaptureImage.Core.Abstractions;
using CaptureImage.Core.Models;
using CaptureImage.ViewModels.Logs;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Xunit;
namespace CaptureImage.ViewModels.Tests.Logs;
/// <summary>
/// Covers the view-side logic of <see cref="LogViewerViewModel"/> — hydration from the
/// buffer source, the live-tail append path, and the min-level filter that feeds the
/// viewer while leaving the underlying sink snapshot intact (so Export stays complete).
/// </summary>
public class LogViewerViewModelTests
{
[Fact]
public void EnsureHydrated_CopiesSnapshotIntoEntries()
{
var source = new FakeBuffer();
source.Feed("one", LogLevel.Information);
source.Feed("two", LogLevel.Warning);
var vm = Build(source);
vm.EnsureHydrated();
vm.Entries.Should().HaveCount(2);
vm.Entries[0].Message.Should().Be("one");
vm.Entries[1].Message.Should().Be("two");
}
[Fact]
public void EnsureHydrated_OnlySecondCallDoesNothing()
{
var source = new FakeBuffer();
source.Feed("a", LogLevel.Information);
var vm = Build(source);
vm.EnsureHydrated();
vm.EnsureHydrated(); // idempotent
vm.Entries.Should().HaveCount(1);
}
[Fact]
public void LiveTail_AppendedEntryAppearsInEntries()
{
var source = new FakeBuffer();
var vm = Build(source);
source.Emit(new LogEntry(
DateTimeOffset.UtcNow,
LogLevel.Information,
"TestCtx",
"live",
Exception: null));
vm.Entries.Should().ContainSingle()
.Which.Message.Should().Be("live");
}
[Fact]
public void FilterChange_DropsLowerLevelEntries_KeepsHigherOnes()
{
var source = new FakeBuffer();
source.Feed("dbg", LogLevel.Debug);
source.Feed("inf", LogLevel.Information);
source.Feed("wrn", LogLevel.Warning);
source.Feed("err", LogLevel.Error);
var vm = Build(source);
vm.EnsureHydrated();
vm.SelectedFilterLevel = LogLevel.Warning;
vm.Entries.Should().HaveCount(2);
vm.Entries.Should().OnlyContain(e => e.Level >= LogLevel.Warning);
}
[Fact]
public void FilterChange_DoesNotTouchUnderlyingBuffer()
{
var source = new FakeBuffer();
source.Feed("a", LogLevel.Debug);
source.Feed("b", LogLevel.Information);
var vm = Build(source);
vm.EnsureHydrated();
vm.SelectedFilterLevel = LogLevel.Error;
vm.Entries.Should().BeEmpty();
// Export path calls Snapshot directly — full set must still be there.
source.Snapshot().Should().HaveCount(2);
}
[Fact]
public void LiveTail_WhenEntryBelowFilter_Suppressed()
{
var source = new FakeBuffer();
var vm = Build(source);
vm.SelectedFilterLevel = LogLevel.Warning;
source.Emit(new LogEntry(
DateTimeOffset.UtcNow, LogLevel.Debug, "Ctx", "quiet", null));
source.Emit(new LogEntry(
DateTimeOffset.UtcNow, LogLevel.Error, "Ctx", "loud", null));
vm.Entries.Should().ContainSingle()
.Which.Message.Should().Be("loud");
}
// -- helpers --------------------------------------------------------------
private static LogViewerViewModel Build(ILogBufferSource source)
{
var dispatcher = Substitute.For<IUIThreadDispatcher>();
dispatcher.When(d => d.Post(Arg.Any<Action>()))
.Do(call => call.Arg<Action>().Invoke());
var localization = Substitute.For<ILocalizationService>();
localization["Log_Pause"].Returns("Pause");
localization["Log_Resume"].Returns("Resume");
localization["Log_EventsCount"].Returns("{0} events");
localization["Log_EmptyState"].Returns("no entries");
localization["Log_Filter"].Returns("min:");
localization["Log_RevealFolder"].Returns("open");
var toasts = Substitute.For<IToastService>();
return new LogViewerViewModel(
source,
dispatcher,
localization,
NullLogger<LogViewerViewModel>.Instance,
toasts);
}
private sealed class FakeBuffer : ILogBufferSource
{
private readonly List<LogEntry> _entries = new();
public IReadOnlyList<LogEntry> Snapshot() => new List<LogEntry>(_entries);
public event EventHandler<LogEntry>? Emitted;
public bool Paused { get; set; }
public void Clear() => _entries.Clear();
public void Feed(string message, LogLevel level)
{
_entries.Add(new LogEntry(
DateTimeOffset.UtcNow, level, "TestCtx", message, Exception: null));
}
/// <summary>Test-only: push an entry as if the live tail fired.</summary>
public void Emit(LogEntry entry)
{
_entries.Add(entry);
Emitted?.Invoke(this, entry);
}
}
}