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);
}
//参数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 + "]");
}
}
}
}
}
这样,有了上面这个写错误日志的类,那么我们就可以在底层与数据库交涉的代码中通过调用WriteLod(,,,,)方法来写错误日志
try
{
... //正常的操作数据库代码
}
catch(Exception ex)
{
WriteLog("日志文件路径","日志文件名",ex.Exception,"发生错误页面名称");
}
浙公网安备 33010602011771号