C#用来写站点日志的类
在web开发中我们常常要记下日志信息,看看站点运营过程中的异常信息,下面这个类是一个简单的写日志类,只是把所有的信息写到log+year+month+day.txt这个文件中.
using System;
using System.Data;
using System.Web;
using System.IO;
/// <summary>
/// 用来写日志的类
/// 本类只提供一个write方法来写日志信息
/// </summary>
public class log
{
private log()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static void write(String msg)
{
try
{
HttpContext ht = HttpContext.Current;
String path = ht.Server.MapPath("~/logs/");
path = path + "log" + DateManage.FormatDate(DateTime.Now, 3)+".txt";//DateManage类中提供按指定格式输出日期的方法
if (!File.Exists(path))
{
Stream fsc = File.Create(path);
fsc.Close();
}
Stream fs = File.Open(path, FileMode.Append);
DateTime dt = DateTime.Now;
String time = dt.ToString();
String userIP = ht.Request.UserHostAddress;
String url = ht.Request.Url.ToString();
String userBrower = ht.Request.Browser.Version;
TextWriter tw = new StreamWriter(fs);
tw.WriteLine("Time:" + time + " IP:" + userIP + " Url:" + url + " Browers:" + userBrower + " Messege:" + msg);
tw.WriteLine();
tw.WriteLine();
tw.Close();
fs.Close();
}
catch (Exception e)
{
HttpContext.Current.Response.Redirect("/err.aspx?msg=" + e.Message);
}
}
}
using System.Data;
using System.Web;
using System.IO;
/// <summary>
/// 用来写日志的类
/// 本类只提供一个write方法来写日志信息
/// </summary>
public class log
{
private log()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static void write(String msg)
{
try
{
HttpContext ht = HttpContext.Current;
String path = ht.Server.MapPath("~/logs/");
path = path + "log" + DateManage.FormatDate(DateTime.Now, 3)+".txt";//DateManage类中提供按指定格式输出日期的方法
if (!File.Exists(path))
{
Stream fsc = File.Create(path);
fsc.Close();
}
Stream fs = File.Open(path, FileMode.Append);
DateTime dt = DateTime.Now;
String time = dt.ToString();
String userIP = ht.Request.UserHostAddress;
String url = ht.Request.Url.ToString();
String userBrower = ht.Request.Browser.Version;
TextWriter tw = new StreamWriter(fs);
tw.WriteLine("Time:" + time + " IP:" + userIP + " Url:" + url + " Browers:" + userBrower + " Messege:" + msg);
tw.WriteLine();
tw.WriteLine();
tw.Close();
fs.Close();
}
catch (Exception e)
{
HttpContext.Current.Response.Redirect("/err.aspx?msg=" + e.Message);
}
}
}