由于项目中大部分代码为javascript代码,有时由于浏览器不同等原因造成开发过程中未能发现的一些bug在用户使用的时候出现,而javascript又无法记录错误日志,一些bug甚至不容易重现,故有需要制作一个javascript日志功能。不多说直接上代码,请大家多拍几砖
JsLogger.js
1 /*
2 javascript 错误日志记录类
3 提供的方法有init,Error,Info,Warn,Debug,
4 Error参数为可选的(customMsg,sysErr,ErrLine),
5 自定义消息,系统的错误消息,错误所在行
6 其它只有customMsg;
7
8 配置项:
9 //初始化配置
10 logger.init();
11 //是否停止日志记录(默认为false,即启用日志记录)
12 logger.disabled=false
13 //是否自动捕捉系统的异常
14 logger.catchWindowError(true);
15 */
16
17 logger=function(){
18 //处理系统错误
19 var formatWindowError=function(sysErr,ErrUrl,ErrLine){
20 try{
21 var errorMsg=" 错误描述:"+sysErr
22 +" url地址:"+ErrUrl
23 +" 错误行:"+ErrLine;
24 send(escape(errorMsg),"Error");
25 }catch(err){
26
27 }
28 }
29 //拼接日志消息
30 var initMsg=function(customMsg,sysErr,ErrLine){
31 var errString=""+customMsg;
32 if(sysErr){
33 errString+=sysErrToString(sysErr)
34 }
35 if(ErrLine){
36 errString+=",行号:"+ErrLine+"。"
37 }
38 errString+=" 浏览器:"+logger.broswerName;
39 return errString;
40 }
41 //取得发送对象
42 var getRequester=function(){
43 var req;
44 if (window.XMLHttpRequest){
45 req = new XMLHttpRequest();
46 try {
47 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
48 }
49 catch (exception){
50 // alert(exception);
51 }
52 }
53 else if (window.ActiveXObject){
54 req = new ActiveXObject("Microsoft.XMLHTTP");
55 }
56 return req;
57 }
58 //检查系统配置
59 var test=function(){
60 if(logger.disabled){
61 return false;
62 }
63 if(!logger.requester){
64 return false;
65 }
66 return true;
67 }
68 //获取文件当前的相对路径
69 var getScriptLocation=function() {
70 var scriptLocation = "";
71 var scriptName = "JsLogger.js";
72 var scripts = document.getElementsByTagName('script');
73 for (var i = 0;i < scripts.length; i++) {
74 var src = scripts[i].getAttribute('src');
75 if (src) {
76 var index = src.lastIndexOf(scriptName);
77 // is it found, at the end of the URL?
78 if ((index > -1) && (index + scriptName.length == src.length)) {
79 scriptLocation = src.slice(0, -scriptName.length);
80 break;
81 }
82 }
83 }
84 return scriptLocation;
85 }
86 //发送信息
87 var send=function(msg,logType){
88 var url=logger.serverURL+"?msg=javascript Message: "+msg+"&logType="+logType
89 logger.requester.open("POST",url,true);
90 logger.requester.setRequestHeader('content-type', 'text/xml');
91 logger.requester.onreadystatechange = onReadyStateChange;
92 logger.requester.send("");//firefox下发送请求必须带参数
93 //alert("send")
94 }
95 //发送信息过程
96 var onReadyStateChange=function(returnValue){
97 // if (logger.requester.readyState != 4){
98 // return;
99 // }
100 // if (logger.requester.status == 200) {
101 // // alert("日志已记录")
102 // } else {
103 //
104 // }
105 }
106 //格式化系统返回的错误信息
107 var sysErrToString=function(err){
108 try{
109 return " 错误描述:"+err.description
110 +" 错误消息:"+err.message
111 +" 错误名称:"+err.name;
112 }
113 catch(err){
114 return "";
115 }
116 }
117 //获取浏览器信息
118 var getBroswerName=function(){
119 var Sys = {};
120 var ua = navigator.userAgent.toLowerCase();
121 var s;
122 (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
123 (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
124 (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
125 (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
126 (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
127
128 if (Sys.ie) return ('IE ' + Sys.ie);
129 if (Sys.firefox) return('Firefox' + Sys.firefox);
130 if (Sys.chrome) return('Chrome' + Sys.chrome);
131 if (Sys.opera) return('Opera ' + Sys.opera);
132 if (Sys.safari) return('Safari' + Sys.safari);
133 }
134
135 return{
136 //服务器处理URL
137 serverURL:null,
138 //是否启用日志记录
139 disabled:false,
140 //日志类型
141 Error:function(customMsg,sysErr,ErrLine){
142 if(!test()){return;}
143 var msg=escape(initMsg(customMsg,sysErr,ErrLine));
144 send(msg,"Error");
145 },
146 Info:function(customMsg){
147 if(!test()){return;}
148 var msg=escape(initMsg(customMsg));
149 send(msg,"Info");
150 },
151 Debug:function(customMsg){
152 if(!test()){return;}
153 var msg=escape(initMsg(customMsg));
154 send(msg,"Debug");
155 },
156 Warn:function(customMsg){
157 if(!test()){return;}
158 var msg=escape(initMsg(customMsg));
159 send(msg,"Warn");
160 },
161 //是否捕获全部系统错误
162 catchWindowError:function(isCatch){
163 if(!isCatch)return;
164 window.onerror=formatWindowError;
165 },
166 init:function(){
167 this.serverURL=getScriptLocation()+"JsLoggerHandler.ashx";
168 this.requester=getRequester();
169 this.broswerName=getBroswerName();
170 }
171 }
172 }();
173
174 logger.init();
175 logger.catchWindowError(true);
2 javascript 错误日志记录类
3 提供的方法有init,Error,Info,Warn,Debug,
4 Error参数为可选的(customMsg,sysErr,ErrLine),
5 自定义消息,系统的错误消息,错误所在行
6 其它只有customMsg;
7
8 配置项:
9 //初始化配置
10 logger.init();
11 //是否停止日志记录(默认为false,即启用日志记录)
12 logger.disabled=false
13 //是否自动捕捉系统的异常
14 logger.catchWindowError(true);
15 */
16
17 logger=function(){
18 //处理系统错误
19 var formatWindowError=function(sysErr,ErrUrl,ErrLine){
20 try{
21 var errorMsg=" 错误描述:"+sysErr
22 +" url地址:"+ErrUrl
23 +" 错误行:"+ErrLine;
24 send(escape(errorMsg),"Error");
25 }catch(err){
26
27 }
28 }
29 //拼接日志消息
30 var initMsg=function(customMsg,sysErr,ErrLine){
31 var errString=""+customMsg;
32 if(sysErr){
33 errString+=sysErrToString(sysErr)
34 }
35 if(ErrLine){
36 errString+=",行号:"+ErrLine+"。"
37 }
38 errString+=" 浏览器:"+logger.broswerName;
39 return errString;
40 }
41 //取得发送对象
42 var getRequester=function(){
43 var req;
44 if (window.XMLHttpRequest){
45 req = new XMLHttpRequest();
46 try {
47 netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
48 }
49 catch (exception){
50 // alert(exception);
51 }
52 }
53 else if (window.ActiveXObject){
54 req = new ActiveXObject("Microsoft.XMLHTTP");
55 }
56 return req;
57 }
58 //检查系统配置
59 var test=function(){
60 if(logger.disabled){
61 return false;
62 }
63 if(!logger.requester){
64 return false;
65 }
66 return true;
67 }
68 //获取文件当前的相对路径
69 var getScriptLocation=function() {
70 var scriptLocation = "";
71 var scriptName = "JsLogger.js";
72 var scripts = document.getElementsByTagName('script');
73 for (var i = 0;i < scripts.length; i++) {
74 var src = scripts[i].getAttribute('src');
75 if (src) {
76 var index = src.lastIndexOf(scriptName);
77 // is it found, at the end of the URL?
78 if ((index > -1) && (index + scriptName.length == src.length)) {
79 scriptLocation = src.slice(0, -scriptName.length);
80 break;
81 }
82 }
83 }
84 return scriptLocation;
85 }
86 //发送信息
87 var send=function(msg,logType){
88 var url=logger.serverURL+"?msg=javascript Message: "+msg+"&logType="+logType
89 logger.requester.open("POST",url,true);
90 logger.requester.setRequestHeader('content-type', 'text/xml');
91 logger.requester.onreadystatechange = onReadyStateChange;
92 logger.requester.send("");//firefox下发送请求必须带参数
93 //alert("send")
94 }
95 //发送信息过程
96 var onReadyStateChange=function(returnValue){
97 // if (logger.requester.readyState != 4){
98 // return;
99 // }
100 // if (logger.requester.status == 200) {
101 // // alert("日志已记录")
102 // } else {
103 //
104 // }
105 }
106 //格式化系统返回的错误信息
107 var sysErrToString=function(err){
108 try{
109 return " 错误描述:"+err.description
110 +" 错误消息:"+err.message
111 +" 错误名称:"+err.name;
112 }
113 catch(err){
114 return "";
115 }
116 }
117 //获取浏览器信息
118 var getBroswerName=function(){
119 var Sys = {};
120 var ua = navigator.userAgent.toLowerCase();
121 var s;
122 (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
123 (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
124 (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
125 (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
126 (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
127
128 if (Sys.ie) return ('IE ' + Sys.ie);
129 if (Sys.firefox) return('Firefox' + Sys.firefox);
130 if (Sys.chrome) return('Chrome' + Sys.chrome);
131 if (Sys.opera) return('Opera ' + Sys.opera);
132 if (Sys.safari) return('Safari' + Sys.safari);
133 }
134
135 return{
136 //服务器处理URL
137 serverURL:null,
138 //是否启用日志记录
139 disabled:false,
140 //日志类型
141 Error:function(customMsg,sysErr,ErrLine){
142 if(!test()){return;}
143 var msg=escape(initMsg(customMsg,sysErr,ErrLine));
144 send(msg,"Error");
145 },
146 Info:function(customMsg){
147 if(!test()){return;}
148 var msg=escape(initMsg(customMsg));
149 send(msg,"Info");
150 },
151 Debug:function(customMsg){
152 if(!test()){return;}
153 var msg=escape(initMsg(customMsg));
154 send(msg,"Debug");
155 },
156 Warn:function(customMsg){
157 if(!test()){return;}
158 var msg=escape(initMsg(customMsg));
159 send(msg,"Warn");
160 },
161 //是否捕获全部系统错误
162 catchWindowError:function(isCatch){
163 if(!isCatch)return;
164 window.onerror=formatWindowError;
165 },
166 init:function(){
167 this.serverURL=getScriptLocation()+"JsLoggerHandler.ashx";
168 this.requester=getRequester();
169 this.broswerName=getBroswerName();
170 }
171 }
172 }();
173
174 logger.init();
175 logger.catchWindowError(true);
服务器端:
JsLoggerHandler.ashx
<%@ WebHandler Language="C#" Class="JsLoggerHandler" %>
using System;
using System.Web;
using System.IO;
using log4net;
using AppBase.Log;
public class JsLoggerHandler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
//Global.mainLog.Error("msg");
string msg = context.Request.QueryString["msg"];
string logType = context.Request.QueryString["logType"];
string user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
msg += " 客户端IP:" + user_IP;
context.Response.ContentType = "text/plain";
bool isOk= WirteLog(msg,logType);
context.Response.Write(isOk.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
private bool WirteLog(string msg, string msgType)
{
if (String.IsNullOrEmpty(msg))
{
return false;
}
try
{
switch (msgType)
{
case "Error":
Global.mainLog.Error(msg);
break;
case "Debug":
Global.mainLog.Debug(msg);
break;
case "Info":
Global.mainLog.Info(msg);
break;
case "Warn":
Global.mainLog.Warn(msg);
break;
default:
Global.mainLog.Error(msg);
break;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
using System;
using System.Web;
using System.IO;
using log4net;
using AppBase.Log;
public class JsLoggerHandler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
//Global.mainLog.Error("msg");
string msg = context.Request.QueryString["msg"];
string logType = context.Request.QueryString["logType"];
string user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
msg += " 客户端IP:" + user_IP;
context.Response.ContentType = "text/plain";
bool isOk= WirteLog(msg,logType);
context.Response.Write(isOk.ToString());
}
public bool IsReusable
{
get
{
return false;
}
}
private bool WirteLog(string msg, string msgType)
{
if (String.IsNullOrEmpty(msg))
{
return false;
}
try
{
switch (msgType)
{
case "Error":
Global.mainLog.Error(msg);
break;
case "Debug":
Global.mainLog.Debug(msg);
break;
case "Info":
Global.mainLog.Info(msg);
break;
case "Warn":
Global.mainLog.Warn(msg);
break;
default:
Global.mainLog.Error(msg);
break;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
代码
public class Global
{
/// <summary>
/// 日志对象
/// </summary>
public static readonly ILog mainLog = GetLog();
private static ILog GetLog()
{
try
{
//获取配置文件路径
string config_file_path = AppDomain.CurrentDomain.BaseDirectory + "log4net.config";
if(System.IO.File.Exists(config_file_path))
{
//加载配置信息
log4net.Config.XmlConfigurator.Configure(
new System.IO.FileInfo(config_file_path));
//生成日志对象
ILog log = LogManager.GetLogger("GlobalLog");
return log;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Print("加载日志对象出错" + ex.Message);
}
return null;
}
}
{
/// <summary>
/// 日志对象
/// </summary>
public static readonly ILog mainLog = GetLog();
private static ILog GetLog()
{
try
{
//获取配置文件路径
string config_file_path = AppDomain.CurrentDomain.BaseDirectory + "log4net.config";
if(System.IO.File.Exists(config_file_path))
{
//加载配置信息
log4net.Config.XmlConfigurator.Configure(
new System.IO.FileInfo(config_file_path));
//生成日志对象
ILog log = LogManager.GetLogger("GlobalLog");
return log;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Print("加载日志对象出错" + ex.Message);
}
return null;
}
}
应用:
logger.Debug("运行到100行");
try{
aa();
}
catch(err){
logger.Error("执行aa()出现错误",err,180);
}
try{
aa();
}
catch(err){
logger.Error("执行aa()出现错误",err,180);
}
下载地址:http://u.115.com/file/t575cf47c3
jsLogger.rar