ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 记录日志文件

记录日志文件

原创 Linux操作系统 作者:taogchan 时间:2013-09-13 16:19:11 0 删除 编辑


    class CommonFuc
    { 
  private static readonly string strLogPath = System.Configuration.ConfigurationSettings.AppSettings["logPath"];//日志路徑

        ///


        /// 用于記錄日志
        ///

        /// 日志path
        /// 日志內容
        public static void WriteLog(string logType, string logInfo)
        {
            string filename = string.Empty;
            switch (logType)
            {
                case "MailLog":
                    filename = strLogPath + @"\MailLogs\" + DateTime.Now.ToString("yyyyMMdd") + "-Notes.log"; ;
                    break;
                case "RuningLog":
                    filename = strLogPath + @"\ServiceLogs\" + DateTime.Now.ToString("yyyyMMdd") + "--B2CService.log";
                    break;
            }
            FileInfo f = new FileInfo(filename);
            FileStream fs = null;
            StreamWriter sw = null;
            Monitor.Enter(typeof(CommonFuc));
            try
            {
                if (f.Exists)
                {
                    fs = new FileStream(filename,FileMode.Append, FileAccess.Write, FileShare.Write);
                }
                else
                {
                    fs = new FileStream(filename,FileMode.Create, FileAccess.Write, FileShare.Write);
                }
                sw = new StreamWriter(fs);
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss :") + logInfo);
                sw.Flush();
            }
            catch (IOException e)
            {

            }
            finally
            {
                sw.Close();
                fs.Close();
                Monitor.Exit(typeof(CommonFuc));
            }
        }

        ///


        /// DELETE LOG
        ///

        ///
        public static void DeleHistoryLog(double days)
        {
            string del = "ServiceLogs,MailContent1,MailLogs";
            foreach (string item in del.Split(','))
            {
                DirectoryInfo dir = new DirectoryInfo(strLogPath + @"\" + item);
                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo f in files)
                {
                    if (DateTime.Now.AddDays(days).CompareTo(f.CreationTime) > 0)
                    {
                        f.Delete();
                    }
                }
            } 
        }
}
 //在config中添加路径
 
 <!--日志路徑-->
   
 

//调用

            catch (Exception ex)
            {
                CommonFuc.WriteLog("RuningLog", "異常======>>" + ex.Message + "  SP======>>" + "pk_automial.p_show_mail_info");
            }

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22392018/viewspace-772685/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2009-08-28

  • 博文量
    200
  • 访问量
    1188361