现场表现:更新/重启后头几十秒里本机查询都提示「改问云端」。原因是 hik-worker 的懒启动被安排在 20 秒后,而 UDP 17310 应答由 worker 提供; A 探测不到就只能走云端,偏偏是云任务反过来才把 worker 拉起来,形成死循环。 - worker 自检从启动后 20 秒提前到 3 秒(实测 UDP/TCP 约 5 秒内就绪) - 局域网应答的 UDP 绑定加 30 次重试(约 60 秒),上一条日志里它在重启后 没绑上且没有任何痕迹;现在失败会记「第 N 次重试」和最终放弃 - AppLog 改为独占写 + 失败落本进程旁路文件 log_<日期>.p<pid>.txt, 避免并发写把行写截断(FileShare.ReadWrite 会撕裂行) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
202 lines
6.5 KiB
C#
202 lines
6.5 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Globalization;
|
||
using System.IO;
|
||
using System.Text;
|
||
using System.Threading;
|
||
|
||
namespace YuncangTrace.LocalService.Services;
|
||
|
||
/// <summary>
|
||
/// 进程级日志(托盘 / 登录窗 / 主窗 / HTTP 服务都往这里写)
|
||
///
|
||
/// 只落文件、不再进界面:**按天一个文件** <c>logs\log_2026-09-22.txt</c>,就放在软件目录下
|
||
/// (<see cref="AppContext.BaseDirectory"/>)。装到只读位置(如 Program Files)时自动退回
|
||
/// <c>%LOCALAPPDATA%\YuncangTrace\logs</c>。
|
||
///
|
||
/// 写日志失败绝不能影响主流程 —— 所有 IO 异常都吞掉。
|
||
/// </summary>
|
||
public static class AppLog
|
||
{
|
||
private const string FolderName = "logs";
|
||
|
||
private static readonly object Gate = new();
|
||
private static readonly Encoding Utf8NoBom = new UTF8Encoding(false);
|
||
|
||
private static string? _logDirectory;
|
||
private static int _cleanupState;
|
||
|
||
/// <summary>日志保留天数(超过的按天文件自动删除)</summary>
|
||
public const int KeepDays = 14;
|
||
|
||
/// <summary>日志目录(首次访问时创建)</summary>
|
||
public static string LogDirectory => _logDirectory ??= ResolveDirectory();
|
||
|
||
/// <summary>写入一行日志(按天分文件,多线程安全)</summary>
|
||
public static void Write(string message)
|
||
{
|
||
EnsureCleanup();
|
||
|
||
var now = DateTime.Now;
|
||
var line = $"[{now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
|
||
var name = FileNameOf(now);
|
||
|
||
// 不要用 File.AppendAllText:它按 FileShare.Read 打开,只要日志文件正被
|
||
// 记事本/编辑器/日志工具独占打开,每次写入都会失败(2026-10-21 现场丢了 6 小时日志)。
|
||
//
|
||
// 策略:先用**独占写**打开(避免两个实例同时写导致行被截断),失败就重试;
|
||
// 仍然失败则退到本进程专属的旁路文件,宁可多一个文件也不丢日志。
|
||
if (TryAppend(Path.Combine(LogDirectory, name), line)) return;
|
||
if (TryAppend(Path.Combine(LogDirectory, FileNameOf(now, Environment.ProcessId)), line)) return;
|
||
|
||
Interlocked.Increment(ref _dropped);
|
||
LastDroppedAt = DateTime.Now;
|
||
}
|
||
|
||
private static bool TryAppend(string path, string line)
|
||
{
|
||
for (var attempt = 0; attempt < 3; attempt++)
|
||
{
|
||
try
|
||
{
|
||
using var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);
|
||
var bytes = Utf8NoBom.GetBytes(line);
|
||
stream.Write(bytes, 0, bytes.Length);
|
||
return true;
|
||
}
|
||
catch
|
||
{
|
||
if (attempt < 2) Thread.Sleep(30);
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private static string FileNameOf(DateTime time, int processId)
|
||
=> $"log_{time:yyyy-MM-dd}.p{processId}.txt";
|
||
|
||
private static int _dropped;
|
||
|
||
/// <summary>累计丢弃的日志行数(连旁路文件都写不进去时增长)</summary>
|
||
public static int Dropped => Volatile.Read(ref _dropped);
|
||
|
||
/// <summary>最近一次丢弃日志的时间</summary>
|
||
public static DateTime? LastDroppedAt { get; private set; }
|
||
|
||
/// <summary>进程内只清理一次(后台服务整天不重启也只跑一次)</summary>
|
||
private static void EnsureCleanup()
|
||
{
|
||
if (Interlocked.Exchange(ref _cleanupState, 1) != 0) return;
|
||
Cleanup(KeepDays);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 删除超过 <paramref name="keepDays"/> 天的按天日志(文件名 <c>log_yyyy-MM-dd.txt</c>)。
|
||
/// 删不掉的文件静默跳过。
|
||
/// </summary>
|
||
public static int Cleanup(int keepDays = KeepDays)
|
||
{
|
||
var removed = 0;
|
||
|
||
try
|
||
{
|
||
var dir = LogDirectory;
|
||
if (!Directory.Exists(dir)) return 0;
|
||
|
||
var cutoff = DateTime.Today.AddDays(-Math.Max(keepDays, 1));
|
||
|
||
foreach (var file in Directory.EnumerateFiles(dir, "log_*.txt"))
|
||
{
|
||
var name = Path.GetFileNameWithoutExtension(file);
|
||
if (!name.StartsWith("log_", StringComparison.OrdinalIgnoreCase)) continue;
|
||
if (!DateTime.TryParseExact(name.Substring(4), "yyyy-MM-dd", CultureInfo.InvariantCulture,
|
||
DateTimeStyles.None, out var date)) continue;
|
||
if (date >= cutoff) continue;
|
||
|
||
try
|
||
{
|
||
File.Delete(file);
|
||
removed++;
|
||
}
|
||
catch
|
||
{
|
||
// 个别文件被占用(用户用记事本开着)就跳过
|
||
}
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// 目录不可读:当作没有日志
|
||
}
|
||
|
||
return removed;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 清理日志:删除目录下全部 <c>log_*.txt</c>,返回删掉的文件数。
|
||
/// 当天正在写的文件也能删,下次 <see cref="Write"/> 会重建。
|
||
/// </summary>
|
||
public static int Clear()
|
||
{
|
||
var removed = 0;
|
||
|
||
try
|
||
{
|
||
lock (Gate)
|
||
{
|
||
var dir = LogDirectory;
|
||
if (!Directory.Exists(dir)) return 0;
|
||
|
||
foreach (var file in Directory.EnumerateFiles(dir, "log_*.txt"))
|
||
{
|
||
try
|
||
{
|
||
File.Delete(file);
|
||
removed++;
|
||
}
|
||
catch
|
||
{
|
||
// 个别文件被占用(比如用户用记事本打开着)就跳过
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// 目录不可读:当作没有日志
|
||
}
|
||
|
||
return removed;
|
||
}
|
||
|
||
private static string FileNameOf(DateTime time) => $"log_{time:yyyy-MM-dd}.txt";
|
||
|
||
private static string ResolveDirectory()
|
||
{
|
||
var candidates = new List<string>
|
||
{
|
||
// 首选:软件目录(与 exe 同级)
|
||
Path.Combine(AppContext.BaseDirectory, FolderName),
|
||
|
||
// 兜底:用户数据目录(exe 所在目录不可写时)
|
||
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "YuncangTrace", FolderName),
|
||
};
|
||
|
||
foreach (var dir in candidates)
|
||
{
|
||
try
|
||
{
|
||
Directory.CreateDirectory(dir);
|
||
return dir;
|
||
}
|
||
catch
|
||
{
|
||
// 试下一个
|
||
}
|
||
}
|
||
|
||
return candidates[candidates.Count - 1];
|
||
}
|
||
}
|