asp.net记录错误日志的方法

1、说明

  在调试发布后的asp.net项目时有可能会遇到意想不到的错误,而未能及时的显示。这就需要记录日志来跟踪错误信息,所以写了个简单的记录信息的方法,记录简单的文本信息也可以使用。此方法是以生成文本文件的方式记录的,下面贴出代码

2、代码

需要引用 using System.IO;

byte[] myByte = System.Text.Encoding.UTF8.GetBytes("这里是你想要的记录的文本信息");
string strPath = Server.MapPath("~") + "\\Log\\";
if (!Directory.Exists(strPath))
{
    Directory.CreateDirectory(strPath);
}
string strPathLog = strPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
using (FileStream fsWrite = new FileStream(strPathLog, FileMode.Append))
{
    fsWrite.Write(myByte, 0, myByte.Length);
};

  这里会在项目的根目录下生成一个Log的文件夹,如果没有该文件夹会自动创建

      

3、示例

try {
    int i = Convert.ToInt32("");
}
catch (Exception ex) {
    byte[] myByte = System.Text.Encoding.UTF8.GetBytes(ex.ToString());
    string strPath = Server.MapPath("~") + "\\ErrorLog\\";
    if (!Directory.Exists(strPath))
    {
        Directory.CreateDirectory(strPath);
    }
    string strPathLog = strPath + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
    using (FileStream fsWrite = new FileStream(strPathLog, FileMode.Append))
    {
        fsWrite.Write(myByte, 0, myByte.Length);
    };
}

  

 

作者:小路 QQ:2490024434 
出处:http://www.cnblogs.com/lengzhan/ 
本文版权归【冷战】和博客园所有,欢迎转载收藏,未经作者同意须保留此段声明,否则保留追究法律责任的权利。

posted @ 2016-11-25 09:41  冷战  阅读(2905)  评论(0编辑  收藏  举报