XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;

namespace XFEToolBox.Indexing.Service.Engine;

/// <summary>
/// Bounded, best-effort phase diagnostics in the installer's SYSTEM/Administrators-only directory.
/// No filenames, user paths, search text, or exception messages are written.
/// </summary>
internal sealed class NtfsAuditLog(string dataDirectory)
{
    public const string FileName = "engine-audit.jsonl";
    private const long MaximumBytes = 8 * 1024 * 1024;
    private readonly string path = Path.Combine(dataDirectory, FileName);
    private bool disabled;
    public string RunId { get; } = Guid.NewGuid().ToString("N");

    public void Write(string phase, string? volume, int enumerations, int records, int indexedNames,
        ulong journalId, long startUsn, long nextUsn, int shards, double elapsedMs = 0, bool? cacheRestored = null)
    {
        if (disabled) return;
        try
        {
            using var priority = new NtfsIoPriority();
            // Keep at most one previous 8 MiB generation; these are exclusively service-owned logs.
            if (File.Exists(path) && new FileInfo(path).Length >= MaximumBytes)
                File.Move(path, path + ".previous", overwrite: true);
            var line = JsonSerializer.SerializeToUtf8Bytes(new
            {
                timestampUtc = DateTimeOffset.UtcNow,
                runId = RunId,
                phase,
                volume,
                mftEnumerations = enumerations,
                records,
                indexedNames,
                journalId = journalId.ToString("X16"),
                startUsn,
                nextUsn,
                shards,
                elapsedMs = Math.Round(elapsedMs, 3),
                cacheRestored
            });
            using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, 4096);
            stream.Write(line);
            stream.WriteByte((byte)'\n');
        }
        catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException
            or System.Security.SecurityException)
        {
            // A full disk or diagnostics ACL issue must not stop indexing or produce repeated exceptions.
            disabled = true;
        }
    }

    public static string PublicVolumeIdentity(NtfsVolume volume) => volume.Root.Length == 3
        && char.IsAsciiLetter(volume.Root[0]) && volume.Root[1] == ':' ? volume.Root : volume.VolumeId;
}