C# 程序出现错误或异常,将异常信息写入指定日志文件
时间:2010-09-27 来源:jkyweb
C#程序当出现异常时,往往是在页面上出现异常提示的,我们可以将程序中所有出现的异常信息写入到指定的错误日志文件里,这样当网站程序出错时,我们可以直接通过查看错误日志,来分析所有的异常。方便,快捷
using System;
using System.IO;
/// <summary>
/// log 的摘要说明。
/// </summary>
public class NetLog
{
public NetLog()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
//添加文本
public void WriterLog(string path, string logName, string log)
{
string page = "";
WriterLog(path, logName, log, page);
}
public void WriterLog(string path, string logName, string log,string page)
{
System.DateTime tm = DateTime.Now;
string p = path + logName;
if (!Directory.Exists(path))//判断路径下目录是否存在
{
Directory.CreateDirectory(path);
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
sw.WriteLine(log + "----------" + tm + "[" + page + "]");
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine(log + "----------" + tm + "[" + page + "]");
}
}
}
else
{
if (!File.Exists(p))
{
using (StreamWriter sw = File.CreateText(p))
{
sw.WriteLine(log + "----------" + tm + "[" + page + "]");
}
}
else
{
using (StreamWriter sw = File.AppendText(p))
{
sw.WriteLine(log + "----------" + tm + "[" + page + "]");
}
}
}
}
}
相关阅读 更多 +










