// 日志记录类的log方法
function log(err) {
// 查看特性
if (window.XMLHttpRequest) this.req = new XMLHttpRequest();
else if (window.ActiveXObject) this.req =new ActiveXObject("Microsoft.XMLHTTP");
else return; // 失败了
// 设置方法和URI
this.req.open("POST", "/cgi-bin/AjaxLogger.cgi");
// 设置请求头信息。REFERER 是顶层URI,如果它发生在一个包含的.js文件中
// 那么它的位置与错误的位置可能不同
this.req.setRequestHeader(’REFERER’, location.href);
this.req.setRequestHeader(’content-type’, ’text/xml’);
// 请求完成的时候调用的函数
this.req.onreadystatechange = errorLogged;
this.req.send(this.errorToXML(err));
// 如果请求在10秒钟内没有完成,就出现一些错误消息
this.timeout = window.setTimeout("abortLog();", 10000);
} |
类的最后一部分建立了一个Logger类实例。这个类应该只有一个实例。
// 只有一个日志记录器实例
var logger = new Logger(); |
最后的两个函数只是用于琐碎事务管理的。如果在记录错误的时候出现了问题,除了干扰用户之外,我们几乎不能做任务事务。但是,这种情况永远不会出现。这些不是类的方法,因为事件没有指向我们的对象的指针,但是它会指向我们建立的logger实例。
// 我们试过了,但是连接错误,没有希望了
function abortLog() {
logger.req.abort();
alert("Attempt to log the error timed out.");
}
// 请求的状态发生改变的时候调用
function errorLogged() {
if (logger.req.readyState != 4) return;
window.clearTimeout(logger.timeout);
// 请求完成了
if (logger.req.status >= 400)
alert(’Attempt to log the error failed.’);
} |
前面的所有代码都被包装到一个.js文件中了,我们可以在站点的任何(或每一个)页面中包含这个文件。下面是如何包含这个文件的例子:
<script type="text/javascript" src="Logger.js"></script>
<script type="text/javascript">
function trapError(msg, URI, ln) {
// 在对象中包装我们未知的错误
var error = new Error(msg);
error.location = URI + ’, line: ’ + ln; // 添加自定义属性
logger.log(error);
warnUser();
return true; // 停止黄色三角形
}
window.onerror = trapError;
function foo() {
try {
riskyOperation();
} catch (err) {
//添加自定义属性
err.location = location.href + ’, function: foo()’;
logger.log(err);
warnUser();
}
}
function warnUser() {
alert("An error has occurred while processing this page."+"Our engineers have been alerted!");
location.href = ’/path/to/error/page.html’;
}
</script> |
现在你已经知道如何把日志记录器集成到HTML页面中了,剩余的工作就是定义一种接收和转换消息的方法了。我选择使用最底层的通用命名方法,在Perl中建立了一个CGI脚本,这个脚本使用了我喜欢的一些模块,它使用XML::Simple来分析post数据,使用CGI::Carp把结果直接导入到httpd错误日志,这样可以节约系统管理员的时间,因为他不需要查看另外一个日志了。这个脚本还包含了很多良好的示例,它们适当地记录了不同的成功和失败条件。
use CGI;
use CGI::Carp qw(set_progname);
use XML::Simple;
my $request = CGI->new();
my $method = $request->request_method();
# 方法必须是POST
if ($method eq ’POST’) {
eval {
my $content_type = $request->content_type();
if ($content_type eq ’text/xml’) {
print $request->header(-status =>’415 Unsupported Media Type’, -type => ’text/xml’);
croak "Invalid content type: $content_type\n";
}
# 如果方法是POST,内容既不是URL编码也不是多部分形式,
#那么整个post会被填充到一个参数中:POSTDATA。
my $error_xml = $request->param(’POSTDATA’);
my $ref = XML::Simple::XMLin($error_xml);
my ($name, $msg, $location) =($ref->{’name’}, $ref->{’message’}, ’’);
$location = $ref->{’location’} if (defined($ref->{’location’}));
# 改变日志中的名字
set_progname(’Client-side error’);
my $remote_host = $request->remote_host();
carp "name: [$name], msg: [$msg], location: [$location]";
};
if ($@) {
print $request->header(-status => ’500 Internal server error’,-type => ’text/xml’);
croak "Error while logging: $@";
} else {
# 这部分响应代码表明操作成功了,但是客户端不应该期待任何内容
print $request->header(-status => ’204 No content’,-type => ’text/xml’);
}
} else {
print $request->header(-status => ’405 Method not supported’,-type => ’text/xml’);
croak "Unsupported method: $method";
} |
已经完成了!现在,当某些难以理解的JavaScript进入系统的时候,你就可以期待着自己的日志监视器开始闪红灯,你的客户端开发人员在深夜接到电话了。