php 簡單日誌搜索

<?php

/*
	功能 : 實現從壓縮日誌中找出相關的信息
	要求 : php要安裝相關的壓縮擴展
	
*/

$dateTime = new \DateTime();
$dateInterval = \DateInterval::createFromDateString('-1 day');
$datePeriod =  new \DatePeriod($dateTime,$dateInterval,30);

$file_path = '/var/log/nginx/';
$file_prefix = "error.log";
$file_surfix = "gz";
$search_string  = "172.16.149.1";


// 時間要轉換的.
foreach ($datePeriod as $key => $value) {
		$file = $file_path.$file_prefix."-".$value->format('Ymd').".".$file_surfix;	

		if(file_exists($file))
		{
			$handler = fopen($file,"rb");
			stream_filter_append($handler,'zlib.inflate');
			while(feof($handler) !== true)
			{
				$line = fgets($handler);
				if($line === false)
				{
					continue;
				}
				// 定位日以內中的須要的內容.
				if(strpos($line,$search_string) !== false)
				{
					fwrite(STDOUT,$line);
				}
			}
			fclose($handler);	
		}	
}


?>
相關文章
相關標籤/搜索