Exception Error log

 public class ExceptionsHandler
    {
        /// <summary>
        /// 写错误日志
        /// </summary>
        /// <param name="e">Exception</param>
        public static void WriteError(Exception e)
        {
            try
            {
                //每天创建一个错误日志,到服务器虚拟目录下
                string path = "~/Error/" + DateTime.Today.ToString("yyyy-MM-dd") + ".log";
                if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
                {
                    ///如果文件不存在,则创建Log
                    File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
                }
                //写日志文件
                using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
                {
                    //写详细错误信息
                    w.WriteLine("Error Recode:");
                    w.WriteLine("\tError Time:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    w.WriteLine("\tError Address:" + System.Web.HttpContext.Current.Request.Url.ToString());
                    w.WriteLine("\tTarget Site:" + e.TargetSite);
                    w.WriteLine("\tError Message:" + e.Message);
                    w.WriteLine("\tError InnerMessage:" + e.InnerException.Message);
                    w.WriteLine("\tError HelpLink:" + e.HelpLink);
                    w.WriteLine("\tError StackTrace:" + e.StackTrace);
                    w.WriteLine("************************************************************************************");
                    w.WriteLine("\r\n");
                    w.Flush();
                    w.Close();
                }
            }
            //不需要抛出异常
            catch (Exception)
            {
                //throw new Exception("写日志出错!" + ex.Message);
            }
        }
    }

 

posted @ 2013-01-07 09:50  Areas  阅读(220)  评论(0编辑  收藏  举报