2014-01-23 77 views
0

過去幾天我一直陷在這裏。我已經搜索和搜索,但只發布了部分作品的示例和技巧,其中沒有一個是循環的。基本上我想要做的是爲Apache日誌文件做一個過濾器。通過以下代碼,我可以將Apache日誌分爲基本塊。使用這些塊我想創建過濾器。在foreach循環中過濾數組

<?php 

$out = array(); 

exec('tail -n 5 /var/log/httpd/error_log',$out); 



    foreach($out as $output){ 
    preg_match('~^\[(.*?)\]~',$output,$date); 
    preg_match('~\ \[([a-z]*?)\] ~',$output,$type); 
    preg_match('~\ \[client ([0-9\.]*)\]~',$output,$client); 
    preg_match('~[a-z\A-Z\.0-9][^\]]*$~',$output,$message); 


echo "</br>"; 
echo "Date chunk = "; 
print_r($date[0]); 

echo "</br>"; 
echo "Type chunk = "; 
print_r($type[0]); 

echo "</br>"; 
echo "Client chunk ="; 
print_r ($client[0]); 

echo "</br>"; 
echo "Message chunk = "; 
print_r ($message[0]); 

echo "</br>"; 


} 


?> 

這是一個截圖。

http://i.imgur.com/BAZaWDc.png

在apache的日誌文件,則類型塊可以是[錯誤]或[注意],我想有一個方法來過濾日誌文件並進行查看。例如,我只希望包含[error]類型的日誌出現,或者鍵入[Notice]出現,即使日期塊可以用作過濾器來查看來自不同日子的日誌。我可以做一個PHP下拉選項,使用戶選擇[錯誤]或[通知],但我如何使用它們篩選出日誌並查看它們?

回答

0

感謝來自你們倆會有很多人,非常有益的見解。經過一段時間的頭腦風暴後,我認爲直接從centos實現一個方法會更好,而不是完整的php。我發佈任何其他人可能會發現這有幫助的方法

您可以使用Bash/PHP來填充$ Day變量,它應該在Sun,只有1000行中的$ Day。 awk的美妙之處在於你可以通過Date/type/ip =來調整它,只需要改變$ 1到$ 2,$ 3等,並將$ Day變量更改爲正確的類型。

tail -n 1000 /var/log/httpd/error_log | awk -F " " '{if $1 =="[Tue") print $all}' 

對於php,您需要轉義。

"tail -n 1000 /var/log/httpd/error_log | awk -F \" \" '{if $1 == \"[$Day\") print $all}'" 
0

這裏正則表達式爲您(preg_match_all使用它):

(\[[^\]]+\])\s(\[[^\]]+\])\s(\[[^]]+\]):\s([^$]+) 

與此字符串,例如

[Thu Jan 23 02:00:48 2014] [error] [mod_geoip]: Error while opening data file 

preg_match_all返回

Array 
(
[0] => Array 
    (
     [0] => [Thu Jan 23 02:00:48 2014] [error] [mod_geoip]: Error while opening data file 
    ) 

[1] => Array 
    (
     [0] => [Thu Jan 23 02:00:48 2014] 
    ) 

[2] => Array 
    (
     [0] => [error] 
    ) 

[3] => Array 
    (
     [0] => [mod_geoip] 
    ) 

[4] => Array 
    (
     [0] => Error while opening data file 
    ) 

) 
0

假設你有一個過濾器形式使用以下值,您將正確執行必要的輸入驗證:

Log Type : error, notice(select options) 
start date : filter start date() 
end date : filter end date 

而在你的PHP文件

$search_type = isset($_POST['log_type'])?"[".$_POST['log_type']."]":FALSE; 
$start_date = isset($_POST['start_date'])?$_POST['start_date']:FALSE; 
$end_date = isset($_POST['end_date'])?$_POST['end_date']:FALSE; 
$result= array(); 
foreach($out as $output){ 
    $fl = false; 
    $tempStr = substr(substr($date[0],0,-1),1); 
    .................. 
    .................... 
    if($search_type && ($type[0]==$search_type){ 
     $fl = true; 
    } 
    if($start_date){ 
     if(strtotime($start_date." 0:0:0 ") >= strtotime($tempstr)){ 
      $fl=true; 
     } 
    } 
    if($end_date){ 
     if(strtotime($end_date." 0:0:0 ") <= strtotime($tempstr)){ 
      $fl=true; 
     } 
    } 
    if($fl==true){ 
    $result[] = array('date'=>date[0],'type'=>$type[0],'client'=>$client[0],'message'=>$message[0]); 
    } 
} 

的print_r($結果;)