Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP apache error log highlighter
#!/usr/bin/php
<?php
/**
* Usage: tail -f /var/log/apache2/error.log | php-log-highlight
*/
ini_set('display_errors', E_ALL & ~E_STRICT);
// Dependencies
require_once 'Console/Color.php';
$input = fopen('php://stdin', 'r');
do {
$line = fgets($input);
if ($line) {
cprint(highlight_log_line($line));
} else {
usleep(200);
}
} while (true);
function cprint($str) {
print Console_Color::convert($str);
}
function highlight_log_line($line) {
// Escape %'s for Console_Color
$line = preg_replace('/%/', '%%', $line);
// Remove referer
$line = preg_replace('/, referer: .+$/', '', $line);
// Remove [error]
$line = preg_replace('/(\[error\]) /', '', $line);
// Remove [client ...]
$line = preg_replace('/(\[client[^\[\]]+\]) /', '', $line);
// Highlight and simplify timestamp
$line = preg_replace('/\[[^\[\]]+(\d{2}:\d{2}:\d{2})[^\[\]]+\] /', '[%y\\1%n] ', $line);
// Highlight depth in stack traces and file and line number
$line = preg_replace('/( #\d+) (.*)\((\d+)\):/', '%g\\1%n %b\\2%n [%g\\3%n]', $line);
// Highlight depth in stack traces, non files
$line = preg_replace('/( #\d+)/', '%g\\1%n', $line);
// Highlight PHP Stack trace: head
$line = preg_replace('/PHP (Stack trace):/', 'PHP %g\\1%n:', $line);
// Highlight PHP error type and message
$line = preg_replace('/PHP ([a-zA-Z]+): (.*) in (.*) on line (\d+)/', 'PHP %r\\1%n: %k\\2%n in %b\\3%n [%g\\4%n]', $line);
// Highlight PHP Fatal error:
$line = preg_replace('/PHP (Fatal error): (.*) in (.*) on line (\d+)/', 'PHP %R\\1%n: %k\\2%n in %b\\3%n [%g\\4%n]', $line);
// Highlight PHP Fatal error stack trace lines
$line = preg_replace('/PHP\s+(\d+)\.\s+([^\s]+)\s+(.*):(\d+)/', '%g#\\1%n %b\\3%n [%g\\4%n] \\2', $line);
// Strip paths relative to cwd
$line = preg_replace('/' . preg_quote(getcwd(), '/') . '\//', '', $line);
return $line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.