使用PHP调用Httpwatch.controller 来分析httpwatch的log文件

httpwatch 的帮助文档中有关于使用javascript和ruby 、c#来分析httpwatch的log文件的例子,但是还没有PHP的;最开始我使用javascript来写了一点,但是在解析 Request.Stream 和Response.Stream时遇到了问题,不知道该怎么解,因为Stream是字节数组的形式出现的,怎么才能变成字符串呢?尤其是当 Response是gzip压缩过的,用javascript就更不好分析了,于是就想到了PHP。下面是PHP的一个小例子:

—— httpwatch.log.php ———–
<?php
$ct 
= new COM("HttpWatch.Controller");
$log = $ct->OpenLog($argv[1]);
echo  
"The log file contains " . $log->Entries->Count . " entries\n";
$entries = $log->Entries;
$cnt = $log->Entries->Count;
for (
$i = 0 ; $i < $cnt; $i++) {
    
$entry = $entries->item($i);  // item is a method , not a array
    
echo $entry->ClientIp .":" . $entry->ClientPort. "n";
    echo 
"=========== Request Stream =============n";
    echo 
decode($entry->Request->Stream);
    echo 
"\n";
    echo 
"\n";
    echo 
$entry->ServerIp .":". $entry->ServerPort ."n";
    echo 
"=========== Response Stream =============n";
    
$arrResponse = getResponse($entry);
    echo 
$arrResponse["header"];
    echo 
"\n\n";
    echo 
$arrResponse["content"];
    echo 
"\n";
    echo 
"\n";
    echo 
"\n";
}

function getResponse($entry) {
    
$stream = decode($entry->Response->Stream);
    
$pos = strpos($stream, "\r\n\r\n");
    
$header = substr($stream, 0, $pos);
    
$content = substr($stream, $pos + 4);
    
$arrHeaders = getHeader($entry, "Response");
    if (
$arrHeaders["Transfer-Encoding"] == "chunked") {
        
$content = getChunkedContent($content);
    }
    if (
$arrHeaders["Content-Encoding"] == "gzip") {
        
$content = gzuncompress($content); 
// 目前这里是有问题的,不知道为什么
    }
    return array(
"header"=>$header, "content"=>$content);
}

function getChunkedContent($content) {
    
$start = 0;
    
$result = "";
    while(
1) {
        
$pos = strpos($content, "\r\n", $start);
        
$size = hexdec(substr($content, $start, $pos - $start));
        if (
$size == 0) break;
        
$result .= substr($content, $pos + 2, $size);
        
$start = $pos + 2 + $size + 2;
    }
    return 
$result;
}
function 
getHeader($entry, $type) {
    
$cnt = $entry->$type->Headers->Count;
    for (
$i = 0; $i < $cnt; $i++) {
        
$header = $entry->$type->Headers->item($i);
        
$arrResult[$header->Name] = $header->Value;
    }
    return 
$arrResult;
}
function 
decode($stream) {
    
$cnt = count($stream); // 非常注意: 这里用strlen是不行的
    
for( $i = 0 ; $i < $cnt ; $i ++) {
        
$result .= chr($stream[$i]);
    }
    return 
$result;
}

?>

运行: php httpwatch.log.php a.hwl

留下评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据。