在java web开发中,在服务端我们比较常用Log4j来进行写日志的控制,而在客户却多用alert来将中间的结果show出来,十分不方便,为此,我整理了一个在客户端通过javascript来进行写日志脚本,其使用方式与Log4j相似.
1.javascript写日志组件脚本,可将其放在一个js文件中,如:clientlog.js,其代码如下:
/**
* write log at web client ,use javascript
* @author Felix liang
* @email:lxfneer@163.com
*/
function Logger(FileName,logFile){
if(logFile!=null)
this.logFileName=logFile;
else
this.logFileName="c:\\clien_log.txt"; //default log file
this.Prior=0;//0:ALL,1:DEBUG,2:INFO,3:WARN,4:ERROR,5:FATAL,6:OFF
this.FileName=FileName;
this.debug=writeDebug;
this.info=writeInfo;
this.warn=writeWarn;
this.error=writeError;
this.fatal=writeFatal;
this.writeLogFuc=writeLog;
this.isDebugEnabled =function(){return checkDebug(this.Prior,1);}
this.isInfoEnabled =function(){return checkDebug(this.Prior,2);}
this.isWarnEnabled =function(){return checkDebug(this.Prior,3);}
this.isErrorEnabled =function(){return checkDebug(this.Prior,4);}
this.isFatalEnabled =function(){return checkDebug(this.Prior,5);}
}
function checkDebug(DPri,pri){
if(pri>=DPri)
return true;
else
return false;
}
function writeDebug(info,ex){
if(!this.isDebugEnabled())
return;
this.writeLogFuc("Debug",info,ex);
}
function writeInfo(info,ex){
if(!this.isDebugInfo())
return;
this.writeLogFuc("Info",info,ex);
}
function writeWarn(info,ex){
if(!this.isDebugWarn())
return;
this.writeLogFuc("Warn",info,ex);
}
function writeError(info,ex){
if(!this.isErrorEnabled())
return;
this.writeLogFuc("Error",info,ex);
}
function writeFatal(info,ex){
if(!this.isFatalEnabled())
return;
this.writeLogFuc("Fatal",info,ex);
}
function writeLog(prids,info,ex){
try{
if(this.fso==null)
this.fso=new ActiveXObject("Scripting.FileSystemObject");
}catch(ex2){
alert(ex2);
}
if(!this.fso.FileExists(this.logFileName)){
this.logFile=a;
var a = this.fso.CreateTextFile(this.logFileName);
a.Close();
}
var a = this.fso.OpenTextFile(this.logFileName,8);
var s="";
d = new Date();
s += d.getYear() +"-";
s += (d.getMonth() + 1) +"-";
s += d.getDate() + " ";
var c = ":";
s += d.getHours() + c;
s += d.getMinutes() + c;
s += d.getSeconds() + c;
s += d.getMilliseconds();
a.WriteLine(s+" "+prids+" ("+this.FileName+") - ["+(info==null?"":info)+"]");
if(ex!=null)
a.WriteLine("- "+ex+"");
a.Close();
}
function errortrap(msg,url,line){
glog = new Logger("Globe");
if(glog.isErrorEnabled())
glog.error("URL:"+url+"; Line:"+line+"; Msg:"+msg);
return true;
}
window.onerror=errortrap;
2.对Client Logger 的使用
引入clientlog.js:<script type="text/javascript" language="JavaScript" charset="GBK" src="clientlog.js"></script>
在需要写log的文件中加入如下代码:
<script language="javascript">
//创建客户段日志对象
var log=new Logger("test.html");//默认日志到c:\client_log.txt,如果设置第二个参数将会到指定的路径
</scirpt>
...
在代码中需要添加日志的的地方可进行写日志:
var before_amt=10;
if(log.isDebugEnabled()){
log.debug("此前修改中新增费:_before_amt:"+before_amt);
}
....
3.运行完之后查看日志文件即可看到运行过程中的中间结果
4.在此抛砖引玉,有何高见,欢迎mail me:lxfneer@163.com