点滴积累【C#】---错误日志记录到txt文本里。

效果:点滴积累【C#】---错误日志记录到txt文本里。_第1张图片

描述:将系统中的错误信息,try catch到日志里面。

代码:

【后端代码】

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Configuration;
 4 using System.IO;
 5 using System.Linq;
 6 using System.Web;
 7 
 8 namespace GetLog
 9 {
10     public class WriteLog
11     {
12         private static StreamWriter streamWriter; //写文件  
13 
14         public static void WriteError(string message)
15         {
16             try
17             {
18                 //DateTime dt = new DateTime();
19                 string directPath = ConfigurationManager.AppSettings["LogFilePath"].ToString().Trim();    //获得文件夹路径
20                 if (!Directory.Exists(directPath))   //判断文件夹是否存在,如果不存在则创建
21                 {
22                     Directory.CreateDirectory(directPath);
23                 }
24                 directPath += string.Format(@"\{0}.log", DateTime.Now.ToString("yyyy-MM-dd"));
25                 if (streamWriter == null)
26                 {
27                     streamWriter = !File.Exists(directPath) ? File.CreateText(directPath) : File.AppendText(directPath);    //判断文件是否存在如果不存在则创建,如果存在则添加。
28                 }
29                 streamWriter.WriteLine("***********************************************************************");
30                 streamWriter.WriteLine(DateTime.Now.ToString("HH:mm:ss"));
31                 streamWriter.WriteLine("输出信息:错误信息");
32                 if (message != null)
33                 {
34                     streamWriter.WriteLine("异常信息:\r\n" + message);
35                 }
36             }
37             finally
38             {
39                 if (streamWriter != null)
40                 {
41                     streamWriter.Flush();
42                     streamWriter.Dispose();
43                     streamWriter = null;
44                 }
45             }
46         }
47     }
48 }

【调用】:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GetLog
{
    public partial class testLog : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_Click(object sender, EventArgs e)
        {
            try
            {
                int intStr=Convert.ToInt32(tb.Text);
                tb2.Text ="转换成功:" +intStr.ToString();
            }
            catch (Exception ex)
            {
                WriteLog.WriteError(ex.ToString());
                throw ex;
            }
        }
    }
}

 Demo下载:

 http://files.cnblogs.com/files/xinchun/GetLog.zip

你可能感兴趣的:(txt)