171 lines
5.1 KiB
C#
171 lines
5.1 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}";
|
||
|
||
try
|
||
{
|
||
lock (Gate)
|
||
{
|
||
File.AppendAllText(Path.Combine(LogDirectory, FileNameOf(now)), line, Utf8NoBom);
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// 磁盘满 / 无权限:日志丢了也不能影响功能
|
||
}
|
||
}
|
||
|
||
/// <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];
|
||
}
|
||
}
|