您的位置:首页 > 运维架构 > 网站架构

用C#记录网站日志

2010-10-21 11:22 253 查看
当用户点击一个链接的时候,记录下用户在这个session用点击了这个资源:
在链接中触发onlick函数, onlick=ClickLog(clickLogText), 这是一个用ajax处理的异步请求 。
js文件中的代码:
function ClickLog(clickLogText) {
//alert("fefffffffffffe");
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
xmlHttp.open("GET", "/WriteLog.aspx?text=" + clickLogText, true);
xmlHttp.send(null);
// xmlHttp.onreadystatechange = function() {
// if (xmlHttp.readyState == 4) {
// 不需要界面响应,
// }
// }

其中WriteLog.aspx.cs中的代码是:这里要注意一个多线程的问题,因为多个用户可能同时需要操作一个文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.IO;
namespace Gucas
{
public partial class WriteLog : System.Web.UI.Page
{
static Mutex m_WriteMutex = new Mutex();
protected void Page_Load(object sender, EventArgs e)
{
string text = Request.QueryString["text"];

string fileName = @".\Log\ClickLog" + DateTime.Now.ToString(".yyyMMdd");
writeLine(fileName,text);
}

public void writeLine(string fileName, string dataText)
{
FileStream fs = null;
StreamWriter sw = null;
//用于处理多线程
m_WriteMutex.WaitOne();
try
{
//CHECK文件存在不
if (!File.Exists(fileName))
{
FileStream tempfs = File.Create(fileName);
tempfs.Close();
}
fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.None);
fs.Seek(0, System.IO.SeekOrigin.End);
sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.WriteLine(dataText);
if (sw != null)
{
sw.Close();
sw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
catch (Exception ex)
{
}
finally
{
try
{
if (sw != null)
{
sw.Close();
sw = null;
}
if (fs != null)
{
fs.Close();
fs = null;
}
}
catch
{
}
m_WriteMutex.ReleaseMutex();
}

}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: