107 lines
3.2 KiB
C#
107 lines
3.2 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 开始打印
|
|
/// </summary>
|
|
public FileLogger(string filename, string filePath, int saveDays, string version = null)
|
|
{
|
|
_filename = filename;
|
|
_filePath = filePath.TrimEnd('/') + "/";
|
|
_saveDays = saveDays;
|
|
StartNewFile();
|
|
DeleteOldFile();
|
|
_currentLogDay = CurrentDay;
|
|
|
|
// 在日志开头写入版本号信息
|
|
if (!string.IsNullOrEmpty(version))
|
|
{
|
|
Write($"Version: {version}\n");
|
|
}
|
|
|
|
Write("*********************************************************\nSystem Start at " +
|
|
DateTime.Now.ToString("HH:mm:ss") +
|
|
"\n*********************************************************\n");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 新建文件
|
|
/// </summary>
|
|
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));
|
|
_fileWriter.AutoFlush = true; // 启用自动刷新,实现流式写入
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
} |