您的位置:首页 > 编程语言 > ASP

做个简单的程序日志记录文件

2016-07-19 15:22 465 查看
 public class LogHelper

    {

        /// <summary>

        /// 写入异常信息记录处理

        /// </summary>

        /// <param name="ex">异常信息</param>

        private static void WriteException(string ex)

        {

            try

            {

                //首先删除24小时以前的错误日志

                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(GetRootPath() + "/Log");

                if (dir.Exists)

                {

                    DateTime nt = DateTime.Now.AddDays(-1);

                    foreach (System.IO.FileInfo f in dir.GetFiles())

                    {

                        if (f.CreationTime < nt)

                            f.Delete();

                    }

                }

                else

                {

                    Directory.CreateDirectory(GetRootPath() + "/Log");

                }

                StringBuilder stringBuilder = new StringBuilder();

                stringBuilder.AppendFormat("\n\r-----------------------");

                stringBuilder.AppendFormat("{0},异常信息:-----------------------\n\r", DateTime.Now);

                stringBuilder.AppendFormat("\n\r {0}", ex);

                FileStream fs = new FileStream(string.Format(@"{0}\\{1}/errorLog.txt", GetRootPath(),"Log"), FileMode.Append);

                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);

                stringBuilder.AppendFormat("\n\r\n\r");

                sw.Write(stringBuilder.ToString());

                sw.Dispose();

                fs.Dispose();

            }

            catch { }

        }

        /// <summary>

        /// 取得网站根目录的物理路径

        /// </summary>

        /// <returns></returns>

        private static string GetRootPath()

        {

            string AppPath = "";

            AppPath = AppContext.BaseDirectory;

            

                if (Regex.Match(AppPath, @"\\$", RegexOptions.Compiled).Success)

                    AppPath = AppPath.Substring(0, AppPath.Length - 1);

            

            return AppPath;

        }

        public static void SetBusinessExceptionLog(object str)

        {

            WriteException(str.ToString());

        }

        public static void SetExceptionLog(object str)

        {

            WriteException(str.ToString());

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net asp.net mvc