Created
October 3, 2012 02:22
-
-
Save JCook21/3824561 to your computer and use it in GitHub Desktop.
Singleton class for logging to Graylog
This file contains 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
<?php | |
use Monolog\Logger; | |
use Monolog\Handler\GelfHandler; | |
use Gelf\MessagePublisher; | |
/** | |
* Class to configure and return a Monolog instance | |
* | |
* @author Jeremy Cook | |
*/ | |
class LoggingHelper | |
{ | |
/** | |
* Monolog instance to hold and use | |
* @var Monolog\Logger | |
*/ | |
static protected $instance; | |
/** | |
* Method to return the Monolog instance | |
* | |
* @return Monolog\Logger | |
*/ | |
static public function getLogger() | |
{ | |
if (! self::$instance) { | |
self::configureInstance(); | |
} | |
return self::$instance; | |
} | |
/** | |
* Method to configure the Monolog instance | |
* | |
* @return void | |
*/ | |
static protected function configureInstance() | |
{ | |
self::$instance = new Logger('NAME FOR THIS LOGGER'); | |
self::$instance->pushHandler(new GelfHandler(new MessagePublisher('IP OR DOMAIN NAME OF YOUR GRAYLOG2 SERVER'))); | |
self::$instance->pushProcessor(function ($record){ | |
//Need to filter values in auto-globals | |
//This is because the gelf-php library will not allow 'extra' | |
//values with a key of id to be added | |
$filter = function (array $values) use (&$filter) { | |
$ret = array(); | |
foreach ($values as $key => $value) { | |
if ($key === 'id') { | |
//If the key is id simply continue | |
//NOTE: we should consider how to handle this better. | |
continue; | |
} else if (is_array($value)) { | |
$value = $filter($value); | |
} | |
$ret[$key] = $value; | |
} | |
return $ret; | |
}; | |
if (count($_SERVER)) { | |
$record['extra'] = array_merge($record['extra'], $filter($_SERVER)); | |
} | |
if (count($_GET)) { | |
$record['extra'] = array_merge($record['extra'], $filter($_GET)); | |
} | |
if (count($_POST)) { | |
$record['extra'] = array_merge($record['extra'], $filter($_POST)); | |
} | |
if (count($_COOKIE)) { | |
$record['extra'] = array_merge($record['extra'], $filter($_COOKIE)); | |
} | |
return $record; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment