schramm42
12/10/2013 - 1:24 PM

gistfile1.php

<?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;
        });
    }
}