日志

系统都需要做日志功能,包括系统异常报错、非法访问等等都想要进行记录和统计,这样的数据数量会很多却又跟具体的业务没有太大关系,所以一般情况下可能会选择以txt

 public static void WriteLog(string logstring)
 {
     try
     {
         string path = AppDomain.CurrentDomain.BaseDirectory + "/LOG";
         if (!Directory.Exists(path))
             Directory.CreateDirectory(path);

         path = path + "/log.txt";

         //判断文件是否存在,没有则创建。
         if (!System.IO.File.Exists(path))
         {
             FileStream stream = System.IO.File.Create(path);
             stream.Close();
             stream.Dispose();
         }

         //写入日志
         using (StreamWriter writer = new StreamWriter(path, true))
         {
             writer.WriteLine(DateTime.Now + "  " + logstring);
         }

         long size = 0;
         int isdelete = 0;
         string delName = "";
         List<LogFileInfo> ld = new List<LogFileInfo>();

         //获取文件大小
         using (FileStream file = System.IO.File.OpenRead(path))
         {

             size = file.Length;//文件大小。byte

             //判断日志文件大于20M,换一个新的文件,自动保存5个历史的。
             if (size > (1024 * 1024 * 20)) //(1024 * 1024 * 10)
             {
                 //最多保存5个日志文件,分别是log1.txt log2.txt .....
                 for (int i = 1; i < 5; i++)
                 {
                     string newpath = AppDomain.CurrentDomain.BaseDirectory + "/Log/log" + i + ".txt";
                     //判断文件是否存在,没有则创建。
                     if (!System.IO.File.Exists(newpath))
                     {
                         System.IO.File.Copy(path, newpath, true);
                         isdelete = 1;
                         delName = path;
                         break;
                     }
                     else
                     {
                         FileInfo fi = new FileInfo(newpath);
                         ld.Add(new LogFileInfo() { filepath = newpath, createdate = DateTime.Parse(fi.LastWriteTime.ToString()) });
                         if (i == 4)
                         {
                             ld.Sort((a, b) => a.createdate.CompareTo(b.createdate));
                             if (System.IO.File.Exists(ld[0].filepath))
                             {
                                 System.IO.File.Delete(ld[0].filepath);
                                 FileStream stream = System.IO.File.Create(ld[0].filepath);
                                 stream.Close();
                                 stream.Dispose();
                             }
                             System.IO.File.Copy(path, ld[0].filepath, true);
                             isdelete = 1;
                             delName = path;
                         }
                     }
                 }
             }
         }

         if (isdelete == 1)
         {
             System.IO.File.Delete(path);
         }
     }
     catch (Exception ex)
     {

     }
 }

 

posted @ 2024-06-06 14:58  风中起舞  阅读(11)  评论(0编辑  收藏  举报