Skip to content

Instantly share code, notes, and snippets.

@yrosen
Last active December 10, 2015 06:08
Show Gist options
  • Save yrosen/4392405 to your computer and use it in GitHub Desktop.
Save yrosen/4392405 to your computer and use it in GitHub Desktop.
Replaces PHP's default error handler with one that sends everything to a GELF server (tested with Graylog2)
<?php
/**
* Replaces PHP's default error handler with one that
* sends everything to a GELF server (tested with Graylog2)
*
* From the PHP docs: The following error types cannot be handled with
* a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING,
* E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the
* file where set_error_handler() is called.
*
* ALSO - This requires the GELF PHP library: https://github.com/Graylog2/gelf-php
*
* To use in your app, ensure the GELF lib files are findable by your autoloader or
* load them manually, then include() this file. Also edit the two consts below as
* needed.
*
* TODO: add set_exception_handler now that I know this thing works so far
*
* @author Yehuda Rosen <yrosen@tikvahfund.org>
* @version 1 - 27 Dec 2012
*/
set_error_handler(array('GELFErrorHandler', 'errorHandler'));
class GELFErrorHandler {
// Set these as needed:
const GELF_HOST = '10.10.65.55';
const FACILITY = 'Development site';
static function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) {
$message = new GELFMessage();
// Figure out error level:
switch($errno) {
case E_USER_ERROR:
case E_RECOVERABLE_ERROR:
$errorlevel = GELFMessage::CRITICAL;
break;
case E_WARNING:
case E_USER_WARNING:
case E_DEPRECATED:
$errorlevel = GELFMessage::WARNING;
break;
case E_NOTICE:
case E_USER_NOTICE:
case E_STRICT:
default:
$errorlevel = GELFMessage::NOTICE;
break;
}
// Build GELF message:
$message->setShortMessage($errstr)
->setFullMessage(json_encode(debug_backtrace()))
//->setFullMessage($errstr)
->setHost(gethostname())
->setLevel($errorlevel)
->setFile($errfile)
->setFacility(self::FACILITY)
->setLine($errline);
// Send GELF message:
$publisher = new GELFMessagePublisher(self::GELF_HOST);
$publisher->publish($message);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment