Skip to content

Instantly share code, notes, and snippets.

@avargas
Created November 10, 2011 20:40
Show Gist options
  • Save avargas/1356141 to your computer and use it in GitHub Desktop.
Save avargas/1356141 to your computer and use it in GitHub Desktop.
MongoDB Tail (Graylog2 messages)
<?php
function bash_color($string, $color='white', $background='black') {
$colored_string = "";
$_color['black'] = '0;30';
$_color['dark_gray'] = '1;30';
$_color['blue'] = '0;34';
$_color['light_blue'] = '1;34';
$_color['green'] = '0;32';
$_color['light_green'] = '1;32';
$_color['cyan'] = '0;36';
$_color['light_cyan'] = '1;36';
$_color['red'] = '0;31';
$_color['light_red'] = '1;31';
$_color['purple'] = '0;35';
$_color['light_purple'] = '1;35';
$_color['brown'] = '0;33';
$_color['yellow'] = '1;33';
$_color['light_gray'] = '0;37';
$_color['white'] = '1;37';
$_bg_color['black'] = '40';
$_bg_color['red'] = '41';
$_bg_color['green'] = '42';
$_bg_color['yellow'] = '43';
$_bg_color['blue'] = '44';
$_bg_color['magenta'] = '45';
$_bg_color['cyan'] = '46';
$_bg_color['light_gray'] = '47';
if(isset($_color[$color])) {
$colored_string .= "\033[" . $_color[$color] . "m";
}
if(isset($_bg_color[$background])) {
$colored_string .= "\033[" . $_bg_color[$background] . "m";
}
$colored_string .= $string . "\033[0m";
return $colored_string;
}
function say ($result)
{
static $i = 0;
$i++;
echo bash_color(date('r', $result['created_at']), 'blue');
echo ' #' . $i . ' (' . $result['_id'] . ')';
echo '@' . $result['host'];
echo "\n";
$msg = $result['message'];
$msg = trim(str_replace('#012', "\n", $msg));
foreach (explode("\n", $msg) as $k=>$line) {
echo "\t";
echo $line . "\n";
}
echo "\n";
}
$mongo = new Mongo('mongodb://graylog2:p4ssw0rd@localhost:3002/graylog2');
$table = $mongo->graylog2->messages;
$last = $table->find()->sort(array('_id'=>-1))->limit(2);
$id = false;
foreach ($last as $e) {
$id = $e['_id'];
say($e);
}
$cursor = false;
while (true) {
if (!$cursor) {
echo "creating cursor with $id ... \n";
$cursor = $table->find(array('_id'=>array('$gt'=>$id)))->tailable(true);
}
while (true) {
if (!$cursor->hasNext()) {
if ($cursor->dead()) {
echo "cursor died\n";
break;
}
sleep(1);
continue;
}
$result = $cursor->getNext();
say($result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment