58 lines
1.9 KiB
C#
58 lines
1.9 KiB
C#
using Microsoft.Extensions.Configuration;
|
|
using System;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
/// <summary>
|
|
/// 文件日志写入封装类,自动按日期分文件、超大小自动切割
|
|
/// </summary>
|
|
public class FileLog
|
|
{
|
|
private readonly IConfiguration _configuration;
|
|
private readonly object _lockObj = new object(); // 独立锁,不依赖外部this
|
|
|
|
public FileLog(IConfiguration configuration)
|
|
{
|
|
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 写入日志内容到文件
|
|
/// </summary>
|
|
/// <param name="log">日志文本</param>
|
|
public void WriteToFile(string log)
|
|
{
|
|
try
|
|
{
|
|
// 读取配置,转换最大文件字节数
|
|
int maxMb = _configuration.GetValue<int>("Logging:MaxFileSizeMB");
|
|
long maxFileSizeBytes = (long)maxMb * 1024 * 1024;
|
|
|
|
string today = DateTime.Now.ToString("yyyyMMdd");
|
|
string basePath = _configuration["Logging:LogFileDirectory"];
|
|
Directory.CreateDirectory(basePath);
|
|
|
|
string baseFileName = $"log-{today}";
|
|
string ext = ".log";
|
|
string finalPath = Path.Combine(basePath, $"{baseFileName}{ext}");
|
|
int index = 1;
|
|
|
|
// 文件超限则递增后缀切割
|
|
while (File.Exists(finalPath) && new FileInfo(finalPath).Length >= maxFileSizeBytes)
|
|
{
|
|
finalPath = Path.Combine(basePath, $"{baseFileName}-{index}{ext}");
|
|
index++;
|
|
}
|
|
|
|
// 线程安全写入
|
|
lock (_lockObj)
|
|
{
|
|
File.AppendAllText(finalPath, log + Environment.NewLine, Encoding.UTF8);
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// 原逻辑吞掉所有异常,如需日志可自行增加内部异常输出
|
|
}
|
|
}
|
|
} |