2025-03-29 11:46:48 +08:00

116 lines
4.1 KiB
C#

using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace WindowsFormsApp1
{
// 定义日志条目类
public class LogEntry
{
public DateTime Timestamp { get; set; }
public string Level { get; set; }
public string Message { get; set; }
public string Exception { get; set; }
}
// 封装 CsvHelper 的日志记录类,设为静态类
public static class CsvLogger
{
private static string _baseFilePath;
private static List<string> _customHeaders = new List<string>();
private static readonly object _lockObj = new object(); // 添加锁对象用于线程安全
private static bool _initialized = false;
public static void Initialize(string baseFilePath)
{
if (string.IsNullOrEmpty(baseFilePath))
throw new ArgumentNullException(nameof(baseFilePath), "日志文件路径不能为空");
_baseFilePath = baseFilePath;
_initialized = true;
// 确保目录存在
string directory = Path.GetDirectoryName(baseFilePath);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
}
// 设置自定义表头
public static void SetHeaders(List<string> headers)
{
if (headers == null)
throw new ArgumentNullException(nameof(headers));
lock (_lockObj)
{
_customHeaders = new List<string>(headers); // 创建副本
}
}
private static string GetCurrentLogFilePath()
{
var date = DateTime.Now.ToString("yyyy-MM-dd");
var fileExtension = Path.GetExtension(_baseFilePath);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_baseFilePath);
return $"{Path.GetDirectoryName(_baseFilePath)}/{fileNameWithoutExtension}_{date}{fileExtension}";
}
public static void Log(string csvFormattedString)
{
if (!_initialized)
throw new InvalidOperationException("CsvLogger 未初始化,请先调用 Initialize 方法");
lock (_lockObj)
{
try
{
var filePath = GetCurrentLogFilePath();
bool fileExists = File.Exists(filePath);
// 如果文件不存在,先写入表头
if (!fileExists)
{
using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
if (_customHeaders.Count > 0)
{
foreach (var header in _customHeaders)
{
csv.WriteField(header);
}
csv.NextRecord();
}
else
{
csv.WriteHeader<LogEntry>();
csv.NextRecord();
}
}
}
// 直接写入日志,不使用队列
using (var writer = new StreamWriter(filePath, true, Encoding.UTF8))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
var fields = csvFormattedString.Split(',');
foreach (var field in fields)
{
csv.WriteField(field);
}
csv.NextRecord();
}
}
catch (Exception ex)
{
// 记录错误,但不抛出异常
Console.WriteLine($"写入日志文件时出错: {ex.Message}");
}
}
}
}
}