86 lines
2.8 KiB
C#
86 lines
2.8 KiB
C#
using CsvHelper;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
|
|
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>();
|
|
|
|
public static void Initialize(string baseFilePath)
|
|
{
|
|
_baseFilePath = baseFilePath;
|
|
}
|
|
|
|
// 设置自定义表头
|
|
public static void SetHeaders(List<string> headers)
|
|
{
|
|
_customHeaders = headers;
|
|
}
|
|
|
|
private static string GetCurrentLogFilePath()
|
|
{
|
|
var date = DateTime.Now.ToString("yyyy-MM-dd");
|
|
var fileExtension = Path.GetExtension(_baseFilePath);
|
|
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(_baseFilePath);
|
|
if (!Directory.Exists(Path.GetDirectoryName(_baseFilePath)))
|
|
{
|
|
Directory.CreateDirectory(Path.GetDirectoryName(_baseFilePath));
|
|
}
|
|
return $"{Path.GetDirectoryName(_baseFilePath)}/{fileNameWithoutExtension}_{date}{fileExtension}";
|
|
}
|
|
|
|
public static void Log(string csvFormattedString)
|
|
{
|
|
var filePath = GetCurrentLogFilePath();
|
|
// 检查文件是否存在,如果不存在则创建并写入表头
|
|
if (!File.Exists(filePath))
|
|
{
|
|
using (var writer = new StreamWriter(filePath))
|
|
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))
|
|
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
|
|
{
|
|
var fields = csvFormattedString.Split(',');
|
|
foreach (var field in fields)
|
|
{
|
|
csv.WriteField(field);
|
|
}
|
|
csv.NextRecord();
|
|
}
|
|
}
|
|
}
|
|
}
|