using System; using System.IO; namespace AibisDream.Kit { internal class FileLogger { private StreamWriter _fileWriter; private readonly string _filename; private readonly string _filePath; private readonly int _saveDays; private static string CurrentDay => DateTime.Now.ToString("yyyyMMdd"); private string _currentLogDay; private string _preSavePath; /// /// 开始打印 /// public FileLogger(string filename, string filePath, int saveDays) { _filename = filename; _filePath = filePath.TrimEnd('/') + "/"; _saveDays = saveDays; StartNewFile(); DeleteOldFile(); _currentLogDay = CurrentDay; Write("*********************************************************\nSystem Start at " + DateTime.Now.ToString("HH:mm:ss") + "\n*********************************************************\n"); } /// /// 新建文件 /// private void StartNewFile() { if (_fileWriter != null) { _fileWriter.Close(); _fileWriter.Dispose(); } _fileWriter = null; if (!Directory.Exists(_filePath)) { Directory.CreateDirectory(_filePath); } _fileWriter = File.AppendText(_filePath + string.Format(_filename, DateTime.Now)); } public void Write(string content) { System.Globalization.CultureInfo.CurrentCulture.ClearCachedData(); if (_currentLogDay != CurrentDay) { StartNewFile(); DeleteOldFile(); _currentLogDay = CurrentDay; } if (_fileWriter is { BaseStream: { CanWrite: true } }) _fileWriter.WriteLine(content); } void DeleteOldFile() { var fileList = Directory.GetFiles(_filePath); if (fileList.Length > _saveDays) { _preSavePath = _filePath + string.Format(this._filename, DateTime.Now.AddDays(-_saveDays + 1)); foreach (var t in fileList) { if (string.CompareOrdinal(_preSavePath, t) == 1) { File.Delete(t); } } } } public void OnDestroy() { if (_fileWriter == null) return; Write("*********************************************************\nSystem Shutdown at " + DateTime.Now.ToString("HH:mm:ss") + "\n*********************************************************\n"); _fileWriter.Flush(); _fileWriter.Close(); _fileWriter = null; } } }