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

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

描述:将系统中的错误信息,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 WriteLog11 {12 PRivate static StreamWriter streamWriter; //写文件 13 14 public static void WriteError(string message)15 {16 try17 {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 finally38 {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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航