刘博平的博客

一个软件工程师

php模仿tail实现读取log文件

PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (isset($_GET['ajax'])) {
$this->autoRender = false;
if (RunTime === \App\Library\Resources::Development) {
$handle = fopen(LOGS . 'debug.log', 'r');
} else {
$handle = fopen('/tmp/111.log', 'r');
}
if (isset($_SESSION['offset'])) {
$data = stream_get_contents($handle, -1, $_SESSION['offset']);
$_SESSION['offset'] += strlen($data);
echo nl2br($data);
} else {
fseek($handle, 0, SEEK_END);
$_SESSION['offset'] = ftell($handle);
}
exit();
}

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script src="http://creativecouple.github.com/jquery-timing/jquery-timing.min.js"></script>
<script>
$(function () {
$.repeat(1000, function () {
$.get('/unit/showlog?ajax', function (data) {
var tail = $('#tail');
if (tail.height() > 768)
tail.text(data);
else
tail.append(data);
});
});
});
</script>
<div id="tail">Starting up...</div>