using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Utility.Tools
{
public static class LogFile
{
/// 写LOG到本地文件方法,message="存入信息",path="存储路径"
public static void SaveLogToFile(string message, string path = "./log/defaultlog.txt")
{
FileInfo fi = null;
StreamWriter logWriter = null;
try
{
int fileLength = 1024 * 1024 * 5;//5MB
fi = new FileInfo(path);
if (!fi.Directory.Exists) { fi.Directory.Create(); }
if (fi.Exists && fi.Length > fileLength)
{
string newpath = path.Insert(path.LastIndexOf('.'), "_" + DateTime.Now.ToString("HHmmss"));
File.Move(path, newpath);
}
logWriter = new StreamWriter(path, true);
logWriter.WriteLine(DateTime.Now.ToString() + ">>>" + message);
logWriter.WriteLine("----->.");
}
catch (Exception ex)
{
//throw ex;
}
finally
{
fi = null;
if (logWriter != null)
{
logWriter.Close();
logWriter.Dispose();
}
}
}
//删除指定日期文件,保留7天
public static void DeleteLogs(string Path, int days = 7)
{
//日志保留时长 单位:天
if (days<7)
{
days = 7;
}
try
{
if (!Directory.Exists(Path))
{
return;
}
var now = DateTime.Now;
foreach (var f in Directory.GetFileSystemEntries(Path).Where(f => File.Exists(f)))
{
var t = File.GetCreationTime(f);
var elapsedTicks = now.Ticks - t.Ticks;
var elaspsedSpan = new TimeSpan(elapsedTicks);
if (elaspsedSpan.TotalDays > days)
{
File.Delete(f);
}
}
}
catch (Exception ex)
{
}
}
}
}