系统日志
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Syc.XinLan.Server
{
public static class Comm
{
public static string Plan = string.Empty;//区分判断是理纱,上纱还是配位发的打开的任务
public static string IP = string.Empty;//判断PLC IP地址连接是否正常
public static bool Flage = true; //判断是否开启任务
public static string LabelingPosition = string.Empty; //标签位置
public static string Code = string.Empty;//计划号
/// <summary>
/// 写入日志
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public static string Debug(string content)
{
string folderPath = @"D:\WCS\Log\";
DateTime now = DateTime.Now;
// 使用格式化字符串确保两位数显示
string Y = now.Year.ToString() + "年";
string M = now.Month.ToString("D2") + "月"; // D2格式确保两位数
string D = now.Day.ToString("D2") + "日"; // D2格式确保两位数
string H = now.Hour.ToString("D2"); // D2格式确保两位数
string m = now.Minute.ToString("D2"); // D2格式确保两位数
string s = now.Second.ToString("D2"); // D2格式确保两位数
// 文件夹路径
string path = Path.Combine(folderPath, Y, M, D);
// txt测试报告文件路径
string texPath = Path.Combine(path, "WCSLog.txt");
// 确保目录存在
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// 写入日志内容
string logEntry = $"{Y}{M}{D}{H}时{m}分{s}秒: {content}";
File.AppendAllText(texPath, logEntry + Environment.NewLine, Encoding.UTF8);
// 清理超过7天的日志
CleanupOldLogs(folderPath);
return logEntry;
}
/// <summary>
/// 删除日志信息
/// </summary>
/// <param name="rootFolder"></param>
private static void CleanupOldLogs(string rootFolder)
{
if (!Directory.Exists(rootFolder)) return;
// 计算7天前的日期
DateTime cutoffDate = DateTime.Now.AddDays(-7);
try
{
// 获取所有年份文件夹
foreach (string yearDir in Directory.GetDirectories(rootFolder))
{
int year;
if (!int.TryParse(yearDir.Substring(yearDir.LastIndexOf('\\') + 1).Replace("年", ""), out year))
continue;
// 获取所有月份文件夹
foreach (string monthDir in Directory.GetDirectories(yearDir))
{
int month;
if (!int.TryParse(monthDir.Substring(monthDir.LastIndexOf('\\') + 1).Replace("月", ""), out month))
continue;
// 获取所有日期文件夹
foreach (string dayDir in Directory.GetDirectories(monthDir))
{
int day;
if (!int.TryParse(dayDir.Substring(dayDir.LastIndexOf('\\') + 1).Replace("日", ""), out day))
continue;
try
{
// 尝试解析文件夹日期
DateTime folderDate;
if (DateTime.TryParse($"{year}-{month}-{day}", out folderDate))
{
// 如果日期早于截止日期,删除整个日期文件夹
if (folderDate < cutoffDate.Date)
{
Directory.Delete(dayDir, true);
}
}
}
catch
{
// 忽略解析错误的文件夹
continue;
}
}
// 删除空的月份文件夹
if (Directory.GetDirectories(monthDir).Length == 0 && Directory.GetFiles(monthDir).Length == 0)
{
Directory.Delete(monthDir);
}
}
// 删除空的年份文件夹
if (Directory.GetDirectories(yearDir).Length == 0 && Directory.GetFiles(yearDir).Length == 0)
{
Directory.Delete(yearDir);
}
}
}
catch (Exception ex)
{
// 记录清理错误(可以考虑写入事件日志或主日志文件)
File.AppendAllText(Path.Combine(rootFolder, "cleanup_errors.log"),
$"{DateTime.Now}: 清理旧日志时出错 - {ex.Message}{Environment.NewLine}",
Encoding.UTF8);
}
}
}
}

浙公网安备 33010602011771号