-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfunctions.php
100 lines (75 loc) · 2.66 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
// Tail function
function tailCustom($filepath, $lines = 1, $adaptive = true) {
// Current date
$date = date("Y-m-d H:i:s");
// Open file
$f = @fopen($filepath, "rb");
//if ($f === false) return false;
if ($f === false) return $date." - [ FORKING ] Unable to open file!\n";
// Sets buffer size, according to the number of lines to retrieve.
// This gives a performance boost when reading a few lines from the file.
if (!$adaptive) $buffer = 4096;
else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
// Jump to last character
fseek($f, -1, SEEK_END);
// Read it and adjust line number if necessary
// (Otherwise the result would be wrong if file doesn't end with a blank line)
if (fread($f, 1) != "\n") $lines -= 1;
// Start reading
$output = '';
$chunk = '';
// While we would like more
while (ftell($f) > 0 && $lines >= 0) {
// Figure out how far back we should jump
$seek = min(ftell($f), $buffer);
// Do the jump (backwards, relative to where we are)
fseek($f, -$seek, SEEK_CUR);
// Read a chunk and prepend it to our output
$output = ($chunk = fread($f, $seek)) . $output;
// Jump back to where we started reading
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
// Decrease our line counter
$lines -= substr_count($chunk, "\n");
}
// While we have too many lines
// (Because of buffer size we might have read too many)
while ($lines++ < 0) {
// Find first newline and remove all text before that
$output = substr($output, strpos($output, "\n") + 1);
}
// Close file and return
fclose($f);
return trim($output);
}
// Log rotation function
function rotateLog($logfile, $max_logfiles=3, $logsize=10485760){
// Current date
$date = date("Y-m-d H:i:s");
if(file_exists($logfile)){
// Check if log file is bigger than $logsize
if(filesize($logfile) >= $logsize){
echo $date." - [ LOGFILES ] Log file exceeds size: $logsize. Let me rotate that for you...\n";
$rotate = passthru("gzip -c $logfile > $logfile.".time().".gz && rm $logfile");
if($rotate){
echo $date." - [ LOGFILES ] Log file rotated.\n";
}
}else{
echo $date." - [ LOGFILES ] Log size has not reached the limit yet. (".filesize($logfile)."/$logsize)\n";
}
// Clean up old log files
echo $date." - [ LOGFILES ] Cleaning up old log files...\n";
$logfiles = glob($logfile."*");
foreach($logfiles as $file){
if(is_file($file)){
if(time() - filemtime($file) >= 60 * 60 * 24 * $max_logfiles){
if(unlink($file)){
echo $date." - [ LOGFILES ] Deleted log file $file\n";
}
}
}
}
}else{
echo $date." - [ LOGFILES ] Cannot find a log file to rotate..\n";
}
}