使用php读取日志文件,当文件比较大的时候,会报内存不足,因此应该部分读取,读取指定的行数的数据
php代码:
<?php
class test{
//日志路径
const log_path="e:phpserverapachelogserror.log";
const nginx_log_path="e:phpserver\nginxlogserror.log";
//显示的行数
const pages=50;
public static function main(){
header("content-type:text/html;charset=utf-8");
if(!empty($_get['action'])){
self::$_get['action']();
exit;
}
}
public static function showapachelogs(){
$test=new test();
$result=$test->readlogs(self::log_path,self::pages);
$html="";
foreach($result as $line){
if(strpos($line,"error:")){
$line="<font color='red'>".$line."</font>";
}
$html.="<div class='line'>".$line."<div>";
}
echo $html;
}
public static function shownginxlogs(){
$test=new test();
$result=$test->readlogs(self::nginx_log_path,self::pages);
$html="";
foreach($result as $line){
if(strpos($line,"error")){
$line="<font color='red'>".$line."</font>";
}
$html.="<div class='line'>".$line."<div>";
}
echo $html;
}
/**
* 读取日志
*/
private function readlogs($filepath,$num=20){
$fp = fopen($filepath,"r");
$pos = -2;
$eof = "";
$head = false; //当总行数小于num时,判断是否到第一行了
$lines = array();
while($num>0){
while($eof != "n"){
if(fseek($fp, $pos, seek_end)==0){ //fseek成功返回0,失败返回-1
$eof = fgetc($fp);
$pos--;
}else{ //当到达第一行,行首时,设置$pos失败
fseek($fp,0,seek_set);
$head = true; //到达文件头部,开关打开
break;
}
}
array_unshift($lines,fgets($fp));
if($head){ break; } //这一句,只能放上一句后,因为到文件头后,把第一行读取出来再跳出整个循环
$eof = "";
$num--;
}
fclose($fp);
return array_reverse($lines);
}
}
test::main();
?>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
.logsbox{
margin:5px;
padding: 5px;
width: 600px;
background: #000;
color:#fff;
font-size: 13px;
float: left;
}
.logsbox .line{
margin: 12px 0;
}
</style>
<div class="logsbox apache">
<div class="line">日志读取...</div>
</div>
<div class="logsbox nginx">
<div class="line">日志读取...</div>
</div>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function showlogs(api,showclass){
function readlogs(){
$.ajax({
url:api,
type:"get",
datatype:"text",
success:function(data){
$(showclass).html(data);
}
});
}
readlogs();
setinterval(readlogs,5000);
}
showlogs("?action=shownginxlogs",".nginx");
showlogs("?action=showapachelogs",".apache");
});
</script>
以上这篇php 读取大文件并显示的简单实例(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持硕编程。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!