你的位置:首页 > ASP.net教程

[ASP.net教程]简单的日志管理代码


自己写的记录日志,定期删除日志的方法。

方法比较简单,记录一下吧。

/// <summary>    /// 写日志    /// </summary>    /// <param name="strMsg">内容</param>    /// <param name="strPath">路径(相对hycom下的文件夹路径)</param>    /// <param name="fileName">日志名(默认yyyy-MM-dd.txt)</param>    public static void WriteLog(string strMsg,string strPath,string fileName)    {      string path = AppDomain.CurrentDomain.BaseDirectory + strPath;      if(!path.EndsWith("\\")||!path.EndsWith("/"))      {        path+="\\";      }      if(!Directory.Exists(path))      {        Directory.CreateDirectory(path);      }      DeleteLog(path);      if(fileName=="")      {        fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt";      }      if(!fileName.EndsWith(".txt"))      {        fileName+=".txt";      }      try      {        //string fileName =DateTime.Now.ToString("yyyy-MM-dd") + ".txt";        StreamWriter sw = File.AppendText(path+fileName);        sw.WriteLine("{0}:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"), strMsg);        //sw.WriteLine("\n\r");        sw.Flush();        sw.Close();      }      catch { }    }    /// <summary>    /// 写日志    /// </summary>    /// <param name="strMsg">内容</param>    /// <param name="strPath">路径(相对hycom下的文件夹路径)</param>    public static void WriteLog(string strMsg,string strPath)    {      string fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt";      WriteLog(strMsg,strPath,fileName);    }    /// <summary>    /// 定期删除日志    /// </summary>    /// <param name="strPath">日志路径</param>    private static void DeleteLog(string strPath)    {            if(Directory.Exists(strPath))      {        DirectoryInfo dinfor = new DirectoryInfo(strPath);        FileInfo[] files = dinfor.GetFiles();        foreach(FileInfo file in files)        {          try          {            //删除创建日志日期是3个月前的日志            if(DateTime.Compare(file.CreationTime.AddMonths(3),DateTime.Now)<0)            {              file.Delete();            }            //删除最后修改日志日期是3个月前的日志            if(DateTime.Compare(file.LastWriteTime.AddMonths(3),DateTime.Now)<0)            {              file.Delete();            }            //删除日志名称日期是3个月前的日志            if(DateTime.Compare(Convert.ToDateTime(file.Name.Substring(0,10)),DateTime.Now.AddMonths(-3))<0)            {              file.Delete();            }          }          catch(Exception ex)          {            continue;          }        }      }    }