Skip to content

Instantly share code, notes, and snippets.

@ha1t
Last active December 15, 2015 09:09
Show Gist options
  • Save ha1t/5236118 to your computer and use it in GitHub Desktop.
Save ha1t/5236118 to your computer and use it in GitHub Desktop.
#!/usr/bin/php
<?php
/**
* dietcakeのdebug.logを見るコマンド
*
*/
// 対象のディレクトリがdietcake案件のものか調べてプロジェクトルートを返す
function get_project_dir($dir)
{
while($dir != '/') {
if (file_exists($dir . '/dietcake/dietcake.php')) {
return $dir;
} else {
$dir = dirname($dir);
}
if ($dir === dirname($dir)) {
return false;
}
}
return false;
}
// 行に色をつける
function parse_buffer_debug($line)
{
static $prefix;
$columns = explode("\t", $line);
if (count($columns) < 4) {
return $line;
}
if (!isset($prefix)) {
$prefix = array();
}
// リクエストの開始時には改行が入る
if (strpos($line, "\t1:") !== false) {
$prefix = array();
echo PHP_EOL;
}
// session_idごとに色を変える
$columns[1] = "\x1b[" . get_color($columns[1]) . "m" . $columns[1] . "\x1b[0m";
if (in_array(trim($columns[2]), array('sql', 'cache'))) {
if (trim($columns[2]) === 'cache') {
$columns[2] = "\x1b[" . get_color('c') . 'm' . $columns[2] . "\x1b[0m";
}
// 0.2秒以内に終わってないとred
if ((float)$columns[3] > 0.2) {
$columns[3] = "\x1b[" . get_color('a') . 'm' . $columns[3] . "\x1b[0m";
} else if ((float)$columns[3] > 0.01) {
$columns[3] = "\x1b[" . get_color('c') . 'm' . $columns[3] . "\x1b[0m";
}
preg_match('/^(\d+\:)(\(\w+\))/e', $columns[4], $matches);
$shard_name = $matches[2];
// BEGINを見てトランザクション開始をわかりやすくする
if (strpos($columns[4], 'BEGIN;') !== false) {
$prefix[] = "\x1b[" . get_color($shard_name) . 'm' . '|' . "\x1b[0m";
}
// shardによって色を変える
$columns[4] = preg_replace(
'/^(\d+\:)(\(\w+\))/e',
"'$1' . \"\x1b[\" . get_color('$2') . \"m$2\" . \"\x1b[0m\"",
$columns[4]
);
// prefixをつける
if (count($prefix) > 0) {
$parts = explode(' ', $columns[4]);
$columns[4] = str_replace($parts[0] . ' ', $parts[0] . ' ' . implode('', $prefix), $columns[4]);
}
// COMMITが来たらprefixを減らす
if (strpos($columns[4], 'COMMIT;') !== false) {
array_pop($prefix);
}
}
return implode("\t", $columns);
}
// 引数の内容から適当に色を選んでくれる
function get_color($text)
{
//error_log($text);
$sum = 0;
for ($i = 0; $i < strlen($text); $i++) {
$sum += ord($text{$i});
}
$number = $sum % 16;
$background = 0;
if ($number >= 8) {
$number -= 8;
$background = 1;
}
$number += 30;
return $background . ';' . $number;
}
// 第二匹数でdebug.logが指定されていればそれを利用する
if (isset($argv[1]) && file_exists($argv[1]) && strpos($argv[1], '/tmp/logs/debug.log') !== false) {
$filename = $argv[1];
// 引数指定がない場合、pwd上のプロジェクトのdebug.logを見に行く
} else {
$dir = get_project_dir(getcwd());
if ($dir === false) {
echo "projectが見つかりません。dcプロジェクトの上で実行してください。";
exit;
}
$filename = $dir . '/app/tmp/logs/debug.log';
}
$handle = popen("tail -f {$filename} 2>&1", 'r');
while (!feof($handle)) {
$buffer = fgets($handle);
echo parse_buffer_debug($buffer);
//ob_flush();
//flush();
}
pclose($handle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment