把异常写在日志中

引言:


在项目中我们常常会遇到很多bug,但这些bug不能弹出来给用户看,会降低用户的体验度,所以我们采取用日志记录问题的方法。另外,一个优秀的程序员也是通过增加日志或其他工具以便在程序失败时方便调试。所以,总结这段代码以作分享与记录。



方法:

    

1.在配置文件<configuration><appSettings>中写自己日志的路径。(代码如下)

2.编写记录日志的类

3.在需要try-catch调用的地方调用就好



代码(C#版):

    

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;

namespace GetLog
{
    public class WriteLog
    {
        private static StreamWriter streamWriter;  

        public static void WriteError(Exception ex)
        {
            try
            {
                //在配置文件中获得创建的错误日志文件夹的路径
                string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim();

                //判断文件夹是否存在,如果不存在则创建
                if (!Directory.Exists(directPath))   
                {
                    Directory.CreateDirectory(directPath);
                }
                directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));
                if (streamWriter == null)
                {
                    //判断文件是否存在如果不存在则创建,如果存在则添加。
                    streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath);   
                }

                //记录错误信息
                streamWriter.WriteLine("***********************************************************************");
                streamWriter.WriteLine("时间:" + DateTime.Now.ToString("HH:mm:ss"));
                streamWriter.WriteLine("输出信息:错误信息");
                if (ex.Message != null)
                {                
                    streamWriter.WriteLine("异常信息:" + ex.Message);
                    streamWriter.WriteLine("异常对象:" + ex.Source);
                    streamWriter.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
                    streamWriter.WriteLine("触发方法:" + ex.TargetSite);
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Flush();
                    streamWriter.Dispose();
                    streamWriter = null;
                }
            }
        }
    }
}


配置文件:
<configuration>
  <appSettings>
    <!-- 错误日志保存路径-->
    <add key="LogFilePath" value="D://ErrorLog" />   
  </appSettings>

</configuration>



程序调用:

<span style="white-space:pre">	</span>
        try
            {
                //自己的代码
            }
         catch (Exception ex)
            {
                WriteLog.WriteError(ex);
                //throw ex;
            }


小结:

    

日志文件可以很好的记录程序中的错误,在看这些文件过程中,我们会慢慢成为一个优秀的工程师。当然,从这些错误中,我们不断吸取教训,在今后的工作中尽量在代码编写阶段就避免这些错误。

你可能感兴趣的:(把异常写在日志中)