异常日志以及非异常日志记录方法

 private void WriteLog(Exception ex, string msg, bool flag)
        {
            try
            {
                string fileName = string.Empty;
                if (flag == true)
                {
                    if (!Directory.Exists("没有文件的记录的\\"))
                    {
                        Directory.CreateDirectory("没有文件的记录的\\");
                    }

                    fileName = "没有文件的记录的\\Log.txt";

                    if (!File.Exists(fileName))
                    {
                        StreamWriter sr;
                        sr = File.CreateText(fileName);
                        sr.Close();
                    }
                }
                else
                {
                    if (!Directory.Exists("异常日志\\"))
                    {
                        Directory.CreateDirectory("异常日志\\");
                    }

                    fileName = "异常日志\\errLog.txt";

                    if (!File.Exists(fileName))
                    {
                        StreamWriter sr;
                        sr = File.CreateText(fileName);
                        sr.Close();
                    }

                }

                //定义文件信息对象
                FileInfo finfo = new FileInfo(fileName);

                //判断文件是否存在以及是否大于5M 5242880
                if (finfo.Exists && finfo.Length > 5242880)
                {
                    try
                    {
                        //删除该文件
                        finfo.Delete();
                    }
                    catch
                    {
                    }

                }
                using (StreamWriter writer = new StreamWriter(fileName, true, System.Text.Encoding.UTF8, 1024))
                {
                    writer.WriteLine(String.Empty);


                    if (flag == true)
                    {
                        writer.WriteLine("不存在的影像");
                        writer.WriteLine("记录时间:   {0}", DateTime.Now.ToString());
                        writer.WriteLine("记录信息:   {0}", msg);
                    }
                    else
                    {
                        writer.WriteLine(msg);
                        writer.WriteLine("出错时间:   {0}", DateTime.Now.ToString());
                        writer.WriteLine("出错信息:   {0}", ex.Message);
                        writer.WriteLine("详细信息:   {0}", ex.StackTrace);
                    }
                    writer.WriteLine(String.Empty);
                    writer.WriteLine("*********************************************************************");
                    writer.Flush();
                    writer.Close();
                }
            }
            catch
            {

            }
        }

        /// <summary>
        /// 没找到的文件记录
        /// </summary>
        private void WriteLog(string msg)
        {
            WriteLog(null, msg, true);
        }

 

posted @ 2015-06-03 15:22  洛晨随风  阅读(377)  评论(0编辑  收藏  举报