Created
April 23, 2018 14:26
-
-
Save rsanchez/e9750a41b959b0b1955447ebb6db0151 to your computer and use it in GitHub Desktop.
read logentries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
if (empty($argv[1])) { | |
fwrite(STDERR, 'Usage: read-logentries /path/to/your.log.gz'.PHP_EOL); | |
exit(1); | |
} | |
$file = $argv[1]; | |
if (!file_exists($file)) { | |
fwrite(STDERR, 'File does not exist.'.PHP_EOL); | |
exit(1); | |
} | |
if (!is_readable($file)) { | |
fwrite(STDERR, 'File is not readable.'.PHP_EOL); | |
exit(1); | |
} | |
$function = preg_match('/\.gz$/', $file) ? 'gzopen' : 'fopen'; | |
try { | |
$handle = call_user_func($function, $file, 'r'); | |
} catch (Throwable $e) { | |
fwrite(STDERR, $e->getMessage()); | |
exit(1); | |
} | |
$grep = $argv[2] ?? null; | |
while (($buffer = fgets($handle)) !== false) { | |
try { | |
$data = json_decode($buffer); | |
} catch (Throwable $e) { | |
fwrite(STDERR, json_last_error_msg()); | |
exit(1); | |
} | |
if (isset($data->line) && (!$grep || preg_match('/'.preg_quote($grep).'/', $data->name))) { | |
fwrite(STDOUT, $data->line.PHP_EOL); | |
} | |
} | |
fclose($handle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment