按照日期写入日志(半年清一次)
比较简单的方法,不需要学习组件,只是用简单的文本读取类来实现
public void WriteMessage(Exception msg,String Method)
{
try
{
string mainPath = "D:\\MES_log\\";//日志文件路径&配置到Config文件中直接获取
string path = mainPath;
string filename = DateTime.Now.ToString("yyyyMMdd") + ".txt";//文件名
string year = DateTime.Now.ToString("yyyy");//年
string month = DateTime.Now.ToString("MM");//月
string day = DateTime.Now.ToString("dd");//日
//判断log文件路径是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}
path += year + "\\";
//判断年度文件夹是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}
path += month + "\\";
//判断月度文件夹是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}
path += day + "\\";
//判断当日文件夹是否存在,不存在则创建文件夹
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);//不存在就创建目录
}
//拼接完整文件路径
path += filename;
if (!File.Exists(path))
{
//文件不存在,新建文件
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.Close();
}
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("------------------------------------------------------------------------ Info Start ");
sw.WriteLine("操作时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("出错的方法:" + Method);
sw.WriteLine("异常类型: {0} \r\n", msg.HResult);
sw.WriteLine(" 导致当前异常的 Exception 实例: {0} \r\n", msg.InnerException);
sw.WriteLine(" 导致异常的应用程序或对象的名称: {0} \r\n", msg.Source);
sw.WriteLine(" 引发异常的方法: {0} \r\n", msg.TargetSite);
sw.WriteLine(" 异常堆栈信息: {0} \r\n", msg.StackTrace);
sw.WriteLine(" 异常消息: {0} \r\n", msg.Message);
sw.WriteLine("------------------------------------------------------------------------\r\n");
sw.Flush();
}
}
//当前月份
int totalmonth = int.Parse(month);
int totalyear = int.Parse(year);
int tmonth = 6;//保留日志时长,月度单位
DateTime date;
string datestring = "";
DirectoryInfo dyInfo = new DirectoryInfo(mainPath);
//删除历史数据,保留6个月日志
if (totalmonth < tmonth)
{
//删除前一年totalmonth+6月份之前的数据
datestring = (totalyear - 1).ToString() + "-" + (totalmonth + tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00";
}
else
{
//删除当年6个月前的数据
datestring = (totalyear).ToString() + "-" + (totalmonth - tmonth).ToString().PadLeft(2, '0') + "-" + "01 00:00:00";
}
date = Convert.ToDateTime(datestring);
//获取文件夹下所有的文件
foreach (FileInfo feInfo in dyInfo.GetFiles())
{
//判断文件日期是否小于今天,是则删除
if (feInfo.CreationTime < date)
feInfo.Delete();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
一个具有注脚的文本。1
关注公众号:菊花为啥绽开 ↩︎