using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
/// <summary>
/// SiteLog 表示站点日志
/// </summary>
public class SiteLog
{
/// <summary>
///
/// </summary>
public SiteLog()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
///
/// </summary>
/// <param name="message"></param>
public static void Add(string message)
{
Page page = new Page();
string dir = HttpContext.Current.Server.MapPath("/sitelog");
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string path =dir+"//log" + DateTime.Now.ToString("yyyyMMddHH") + ".txt";
SiteLog sl = new SiteLog();
string timenow = DateTime.Now.ToString();
StringBuilder sb = new StringBuilder();
sb.Append("时间:");
sb.Append(timenow);
sb.Append("/r/n");
sb.Append("信息:");
sb.Append(message);
HttpContext hc = HttpContext.Current;
sb.AppendLine("/r/nIP:" + hc.Request.UserHostAddress);
sb.AppendLine("请求类型:" + hc.Request.HttpMethod);
sb.AppendLine("页面:" + hc.Request.Path);
sb.AppendLine("查询字符串:" + hc.Request.QueryString.ToString());
string cookie="";
for (int i = 0; i < hc.Request.Cookies.Count; i++)
{
HttpCookie c = hc.Request.Cookies[i];
cookie +=(c.Name+"="+c.Value+";");
}
sb.AppendLine("Cookie:" +cookie);
sb.AppendLine("UserAgent:" + hc.Request.UserAgent);
sb.AppendLine("----------------------------------------------------------------------");
if (System.IO.File.Exists(path))
{
try
{
sl.AddMessageToFile(path,sb.ToString());
}
catch (Exception)
{
}
}
else
{
try
{
System.IO.File.Create(path).Close();
}
catch
{
}
try
{
sl.AddMessageToFile(path, sb.ToString());
}
catch
{
}
GC.Collect();
}
}
private void AddMessageToFile(string path, string message)
{
StreamReader sr = new StreamReader(path);
StringBuilder sb = new StringBuilder(sr.ReadToEnd());
sr.Close();
sb.Append(message);
try
{
using (StreamWriter sw = new StreamWriter(path))
{
sw.Write(sb.ToString());
sw.Flush();
sw.Close();
}
}
catch
{
}
}
}