1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- using LJLib.Tools.File;
- using System;
- using System.IO;
- namespace LJLib.TextLog
- {
- internal class ReuestLogger : ILogger
- {
- private readonly string _logDir;
- private readonly object _syncRoot = new object();
- public ReuestLogger(string logDir = null)
- {
- // 默认目录为执行目录下的 log 文件夹
- _logDir = logDir ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log");
- if (!Directory.Exists(_logDir))
- Directory.CreateDirectory(_logDir);
- }
- /// <summary>
- /// 获取今天的日志文件全路径
- /// </summary>
- private string GetTodayLogFile()
- {
- string fileName = $"REQUEST_{DateTime.Now:yyyyMMdd}.log";
- return Path.Combine(_logDir, fileName);
- }
- /// <summary>
- /// 写入日志
- /// </summary>
- public void WriteLog(string msg)
- {
- try
- {
- lock (_syncRoot)
- {
- string filePath = GetTodayLogFile();
- using (StreamWriter sw = new StreamWriter(filePath, true))
- {
- sw.WriteLine("====================================================================");
- sw.WriteLine($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
- sw.WriteLine("--------------------------------------------------------------------");
- sw.WriteLine(msg);
- sw.WriteLine("====================================================================");
- sw.WriteLine();
- }
- // 清理过期日志(7天前的删除)
- CleanupOldLogs();
- }
- }
- catch
- {
- // 这里可考虑写到系统事件日志或忽略
- }
- }
- /// <summary>
- /// 清理7天前的日志文件
- /// </summary>
- private void CleanupOldLogs()
- {
- try
- {
- var files = Directory.GetFiles(_logDir, "REQUEST_*.log");
- DateTime threshold = DateTime.Now.AddDays(-7);
- foreach (var file in files)
- {
- string fileName = Path.GetFileNameWithoutExtension(file);
- // 格式: REQUEST_yyyyMMdd
- if (fileName.Length == "REQUEST_yyyyMMdd".Length &&
- DateTime.TryParseExact(fileName.Replace("REQUEST_", ""),
- "yyyyMMdd",
- null,
- System.Globalization.DateTimeStyles.None,
- out DateTime logDate))
- {
- if (logDate < threshold.Date)
- {
- File.Delete(file);
- }
- }
- }
- }
- catch
- {
- // 忽略清理异常
- }
- }
- }
- }
|