function sendSentryMessage($message) { $CI =& get_instance(); $client = new Raven_Client($CI->config->item('sentry_client_id')); $client->getIdent($client->captureMessage($message)); $client->context->clear(); }
protected function execute(InputInterface $input, OutputInterface $output) { $config = $this->setConfiguraton($input); $client = new \GuzzleHttp\Client(['defaults' => ['allow_redirects' => false, 'timeout' => 5, 'connect_timeout' => 5]]); /** @var Instance $instance */ foreach ($config->getInstances() as $instance) { $requests[] = $client->createRequest('HEAD', $instance->getUrl()); } $options = []; Pool::send($client, $requests, ['complete' => function (CompleteEvent $event) { }, 'error' => function (ErrorEvent $event) use($config) { $instance = $config->findInstanceByUrl($event->getRequest()->getUrl()); if ($instance == null) { throw new \RuntimeException('Instance not found'); } if (!$event->getException()->hasResponse()) { $raven = new \Raven_Client($instance->getSentryDsn()); $event_id = $raven->getIdent($raven->captureMessage(sprintf('The website %s with url -> %s is down or has a problem', $instance->getName(), $event->getRequest()->getUrl()), [], \Raven_Client::FATAL)); if ($raven->getLastError() !== null) { printf('There was an error sending the event to Sentry: %s', $raven->getLastError()); } $error_handler = new \Raven_ErrorHandler($raven); $error_handler->registerExceptionHandler(); $error_handler->registerErrorHandler(); $error_handler->registerShutdownFunction(); } }]); }
/** * Create a new image element from an email address. * @param string $email The email address. * @param integer $size The avatar size. * @return string The source for an image element. */ public static function log($ex) { // Instantiate a new client with a compatible DSN $client = new Raven_Client(Config::get('raven::raven.url')); // Capture an exception $client->captureException($ex); }
/** * Set the user context for the Raven client */ private static function setUserContext() { // Clear the user context self::$_client->context->user = null; // Check if the `AuthComponent` is in use for current request if (class_exists('AuthComponent')) { // Instantiate the user model to get valid field names $modelName = Configure::read('Sentry.user.model'); $user = ClassRegistry::init(empty($modelName) ? 'User' : $modelName); // Check if the user is authenticated $id = AuthComponent::user($user->primaryKey); if ($id) { // Check custom username field (defaults to `displayField` on `User` model) $usernameField = Configure::read('Sentry.user.fieldMapping.username'); if (empty($usernameField)) { $usernameField = $user->displayField; } $extraUserData = array('username' => AuthComponent::user($usernameField)); // Get user emails $emailField = Configure::read('Sentry.user.fieldMapping.email'); $email = !empty($emailField) ? AuthComponent::user($emailField) : null; // Set the user context self::$_client->set_user_data($id, $email, $extraUserData); } } }
/** * {@inheritdoc} */ public function export() { foreach ($this->messages as $message) { list($context, $level, $category, $timestamp, $traces) = $message; $extra = []; if ($context instanceof \Throwable || $context instanceof \Exception) { $this->client->captureException($context); $description = $context->getMessage(); } elseif (isset($context['msg'])) { $description = $context['msg']; $extra = $context; unset($extra['msg']); } else { $description = $context; } if ($this->context) { $extra['context'] = parent::getContextMessage(); } if (is_callable($this->extraCallback)) { $extra = call_user_func($this->extraCallback, $context, $extra); } $data = ['level' => static::getLevelName($level), 'timestamp' => $timestamp, 'message' => $description, 'extra' => $extra, 'tags' => ['category' => $category]]; $this->client->capture($data, $traces); } }
public function captureException($exception, $culpritOrOptions = null, $logger = null, $vars = null) { $eventId = $this->client->captureException($exception, $culpritOrOptions, $logger, $vars); if ($eventId) { $ident = $this->client->getIdent($eventId); $this->recorder->addExceptionEventId($exception, $ident); } return $eventId; }
public function init() { parent::init(); if ($this->enabled) { $user_context = $this->getUserContext(); $this->client->user_context($user_context); $this->client->install(); } }
/** * @param \Exception $e */ public function handleYiiExceptions($e) { if ($this->canLogException($e)) { $e->event_id = $this->client->getIdent($this->client->captureException($e)); } if ($this->oldExceptionHandler) { call_user_func($this->oldExceptionHandler, $e); } }
/** * Handle an error with Sentry * * @return string */ public function handle() { // Instantiate a new Raven_Client with the configured DSN $client = new \Raven_Client(\Skeleton\Error\Config::$sentry_dsn); // Assign the session to the extra context if (isset($_SESSION)) { $client->extra_context(['session' => print_r($_SESSION, true)]); } $client->captureException($this->exception); }
public function handle($e) { if ($e instanceof ErrorException) { $level = $e->getSeverity(); } else { $level = E_ERROR; } if ($this->minimumLogLevel & $level) { $this->client->captureException($e); } }
/** * Exports log [[messages]] to a specific destination. */ public function export() { foreach ($this->messages as $message) { list($msg, $level, $category, $timestamp, $traces) = $message; $levelName = Logger::getLevelName($level); if (!in_array($levelName, ['error', 'warning', 'info'])) { $levelName = 'error'; } $data = ['timestamp' => gmdate('Y-m-d\\TH:i:s\\Z', $timestamp), 'level' => $levelName, 'tags' => ['category' => $category], 'message' => $msg]; if (!empty($traces)) { $data['sentry.interfaces.Stacktrace'] = ['frames' => Raven_Stacktrace::get_stack_info($traces)]; } $this->client->capture($data, false); } }
/** * Logging of errors * * @param $errorMessage * @param $response */ public static function log($errorMessage, $response) { if (is_null(self::$ravenClient)) { self::$ravenClient = new Raven_Client('http://*****:*****@logs.getsitecontrol.com/14'); } self::$ravenClient->captureMessage($errorMessage, array('server' => !empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null, 'code' => !empty($response->info->http_code) ? $response->info->http_code : null, 'response' => !empty($response->response) ? $response->response : null)); }
function sentry_exception_handler($exception) { try { $client = new Raven_Client(SENTRY_DSN, array('curl_method' => 'async', 'verify_ssl' => FALSE)); $client->tags_context(array('source' => 'exception')); $config = Config::Instance(); $event_id = $client->getIdent($client->captureException($exception, array('extra' => array('uzerp_version' => $config->get('SYSTEM_VERSION'))))); $smarty = new Smarty(); $smarty->assign('config', $config->get_all()); $smarty->compile_dir = DATA_ROOT . 'templates_c'; $smarty->assign('event_id', $event_id); $smarty->assign('support_email', SUPPORT_EMAIL); $email_body = "uzERP Exception logged to sentry with ID: " . $event_id; $smarty->assign('email_body', rawurlencode($email_body)); $smarty->display(STANDARD_TPL_ROOT . 'error.tpl'); } catch (Exception $e) { // If something went wrong, just continue. } }
/** * Set user information on the raven context */ protected function setUserContext() { $objectManager = \TYPO3\Flow\Core\Bootstrap::$staticObjectManager; /** @var \TYPO3\Flow\Security\Context $securityContext */ $securityContext = $objectManager->get('TYPO3\\Flow\\Security\\Context'); $userContext = array(); if ($securityContext->isInitialized()) { $account = $securityContext->getAccount(); if ($account !== NULL) { $userContext['username'] = $account->getAccountIdentifier(); } $party = $securityContext->getParty(); if ($party instanceof Person && $party->getPrimaryElectronicAddress() !== NULL) { $userContext['email'] = (string) $party->getPrimaryElectronicAddress(); } elseif ($party !== NULL && ObjectAccess::isPropertyGettable($party, 'emailAddress')) { $userContext['email'] = (string) ObjectAccess::getProperty($party, 'emailAddress'); } } if ($userContext !== array()) { $this->client->user_context($userContext); } }
public function __construct() { $this->errorLevelMap = array('E_NONE' => 0, 'E_ERROR' => 1, 'E_WARNING' => 2, 'E_PARSE' => 4, 'E_NOTICE' => 8, 'E_USER_ERROR' => 256, 'E_USER_WARNING' => 512, 'E_USER_NOTICE' => 1024, 'E_RECOVERABLE_ERROR' => 4096, 'E_ALL' => 8191); $this->settings = get_option('sentry-settings'); if (!isset($this->settings['dsn'])) { return; } if ($this->settings['dsn'] == '') { return; } parent::__construct($this->settings['dsn']); $this->setErrorReportingLevel($this->settings['reporting_level']); $this->setHandlers(); }
/** * Exports log [[messages]] to a specific destination. */ public function export() { foreach ($this->messages as $message) { list($msg, $level, $category, $timestamp, $traces) = $message; $levelName = Logger::getLevelName($level); if (!in_array($levelName, ['error', 'warning', 'info'])) { $levelName = 'error'; } if (is_array($msg)) { if (isset($msg['data'])) { $new_extras = $msg['data']; unset($msg['data']); } if (isset($msg['msg'])) { $new_msg = $msg['msg']; unset($msg['msg']); } else { $new_msg = 'Unknown event format'; // deliver event data even if the format doesn't fit $new_extras = array_merge($new_extras, $msg); $new_tags = ['format' => 'unknown']; } } $data = ['timestamp' => gmdate('Y-m-d\\TH:i:s\\Z', $timestamp), 'level' => $levelName, 'tags' => ['category' => $category], 'message' => isset($new_msg) ? $new_msg : $msg]; if (isset($new_tags)) { $data['tags'] = array_merge($new_tags, $this->client->get_tags(), $this->client->context->extra); } if (isset($new_extras)) { $data['extra'] = array_merge($new_extras, $this->client->tags, $this->client->context->tags); } if (!empty($traces)) { $data['sentry.interfaces.Stacktrace'] = ['frames' => Raven_Stacktrace::get_stack_info($traces)]; } $this->client->capture($data, false); } }
/** * @param string $command * @param int[] $expectedExitCodes * @return int */ public function execWithLogging($command, $expectedExitCodes = array(0)) { $shutUp = ' >/dev/null 2>&1'; exec($command . $shutUp, $output, $exitCode); if (array_search($exitCode, $expectedExitCodes) === false) { $executable = explode(' ', $command, 2); $executable = reset($executable); if ($this->ravenClient) { $this->ravenClient->extra_context(array('command' => $command . $shutUp, 'output' => $output, 'exitCode' => $exitCode)); $this->ravenClient->captureException(new \Exception("{$executable} executed with error")); } return $exitCode; } return $exitCode; }
/** * Log a message to the logs. * * @param string $level * @param mixed $message * @param array $context * * @return void */ public function log($level, $message, array $context = []) { $this->sentry->context->clear(); if ($user = $this->resolveCurrentUser()) { $this->sentry->user_context($user); } $this->sentry->extra_context($context); $level = $this->getSeverity($level); if ($message instanceof Exception) { $this->sentry->getIdent($this->sentry->captureException($message, ['level' => $level])); } else { $msg = $this->formatMessage($message); $this->sentry->getIdent($this->sentry->captureMessage($msg, [], ['level' => $level])); } }
/** * Logs a query to Sentry. * @param string $query query to log. * @param integer $level log level. * @param string $engine name of the sql driver. * @return string event id (or null if not captured). * @throws Exception if logging the query fails. */ public function captureQuery($query, $level = Logger::LEVEL_INFO, $engine = '') { if (!$this->isEnvironmentEnabled()) { return null; } try { $eventId = $this->_client->getIdent($this->_client->captureQuery($query, $level, $engine)); } catch (\Exception $e) { if (YII_DEBUG) { throw new Exception('SentryClient failed to log query: ' . $e->getMessage(), (int) $e->getCode()); } else { $this->log($e->getMessage(), Logger::LEVEL_ERROR); throw new Exception('SentryClient failed to log query.', (int) $e->getCode()); } } $this->_loggedEventIds[] = $eventId; $this->log(sprintf('Query logged to Sentry with event id: %d', $eventId), Logger::LEVEL_INFO); return $eventId; }
public function capture($data, $stack, $vars = null) { // if (class_exists('AuthComponent')) { // $model= Configure::read('Sentry.User.model'); // if (empty($model)) $model = 'User'; // $User = ClassRegistry::init($model); // $mail = Configure::read('Sentry.User.email_field'); // if (empty($mail)) { // if ($User->hasField('email')) $mail = 'email'; // else if ($User->hasField('mail')) $mail = 'mail'; // } // $data['sentry.interfaces.User'] = array( // "is_authenticated" => AuthComponent::user($User->primaryKey) ? true : false, // "id" => AuthComponent::user($User->primaryKey), // "username" => AuthComponent::user($User->displayField), // "email" => AuthComponent::user($mail) // ); // } return parent::capture($data, $stack); }
public function capture($data, $stack, $vars = NULL) { if (class_exists('AuthComponent')) { $model = Configure::read('Sentry.User.model'); if (empty($model)) { $model = 'User'; } $User = ClassRegistry::init($model); $mail = Configure::read('Sentry.User.email_field'); if (empty($mail)) { if ($User->hasField('email')) { $mail = 'email'; } else { if ($User->hasField('mail')) { $mail = 'mail'; } } } $data['sentry.interfaces.User'] = array("is_authenticated" => AuthComponent::user($User->primaryKey) ? true : false, "id" => AuthComponent::user($User->primaryKey), "username" => AuthComponent::user($User->displayField), "email" => AuthComponent::user($mail)); } return parent::capture($data, $stack); }
/** * Log a message to sentry */ public function capture($data, $stack) { if (!Mage::getStoreConfigFlag('dev/amg-sentry/active')) { return true; } if (!empty($data['sentry.interfaces.Message']['params']['description'])) { $data['culprit'] = $data['message']; $data['message'] = $data['sentry.interfaces.Message']['params']['description']; unset($data['sentry.interfaces.Message']['params']['description']); } if (!empty($data['sentry.interfaces.Exception']['value'])) { $data['message'] = $data['culprit']; $data['culprit'] = $data['sentry.interfaces.Exception']['value']; } if (!isset($data['logger'])) { if (null !== self::$_logger) { $data['logger'] = self::$_logger; } else { $data['logger'] = Mage::getStoreConfig('dev/amg-sentry/logger'); } } return parent::capture($data, $stack); }
/** * Send errors to a remote Sentry server with level = warning * * @param array $ferrors * * @return void */ private function sentrySend($ferrors) { //ignore if no username or nagios request if (EGS_USERNAME or strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'nagios') !== false) { try { $client = new Raven_Client(SENTRY_DSN, array('curl_method' => 'async', 'verify_ssl' => FALSE)); // Capture the flash errors and send to Sentry $client->user_context(array('username' => EGS_USERNAME)); $client->tags_context(array('source' => 'flash')); $cc = 0; foreach ($ferrors as $ferror) { $cc++; $client->extra_context(array('error ' . $cc => $ferror)); } if ($cc != 0) { $event_id = $client->getIdent($client->captureMessage($ferrors[0], array(), 'warning')); } } catch (Exception $e) { //If something went wrong, just continue. } } }
/** * @expectedException InvalidArgumentException */ public function testParseDsnMissingSecretKey() { Raven_Client::parseDsn('http://public@example.com/1'); }
/** * Returns the request response from sentry if and only if the last message * was not sent successfully. * * @return mixed Last error */ public function getLastError() { return $this->_client->getLastError(); }
/** {@inheritdoc} */ public function __construct($optionsOrDsn = null, $options = array()) { $options['auto_log_stacks'] = true; parent::__construct($optionsOrDsn, $options); }
public static function notify_admin($e) { if (defined(SENTRY_ENDPOINT)) { require_once JMVC_DIR . 'Raven/Client.php'; require_once JMVC_DIR . 'Raven/Compat.php'; require_once JMVC_DIR . 'Raven/Stacktrace.php'; $client = new Raven_Client(SENTRY_ENDPOINT); $client->captureException($e); exit; } $file = $e->getFile(); $message = self::make_error_report($e->getFile(), $e->getLine(), $e->getMessage()); self::log(date('r') . "\n" . $message, 'php_errors'); $lockfile = LOG_DIR . '/error_state'; $last_notification = file_exists($lockfile) ? filemtime($lockfile) : 0; if ($last_notification == 0 || DEFINED('ADMIN_ALERT_FREQ') && time() - $last_notification > ADMIN_ALERT_FREQ) { touch($lockfile); mail(ADMIN_EMAIL, 'Error in ' . $file, $message); if (defined('ADMIN_ALERT')) { mail(ADMIN_ALERT, 'Error on ' . $_SERVER['HTTP_HOST'], 'check email'); } } }
/* |-------------------------------------------------------------------------- | Application Error Handler |-------------------------------------------------------------------------- | | Here you may handle any errors that occur in your application, including | logging them or displaying custom views for specific errors. You may | even register several error handlers to handle different types of | exceptions. If nothing is returned, the default error view is | shown, which includes a detailed stack trace during debug. | */ App::error(function (Exception $exception, $code) { if (Config::get('sentry.enabled') === true) { // Instantiate a new client with a compatible DSN $client = new Raven_Client(Config::get('sentry.dsn')); $client->getIdent($client->captureException($exception)); } if (Config::get('app.debug') == true) { if (Request::is('api/*')) { return Api::error($exception->getMessage(), $code); } Log::error($exception); } else { if (Request::is('api/*')) { return Api::error(Lang::get('500'), $code); } return Response::view('errors.error', array(), $code); } }); /*
/** * Export the message * * @param array $content Array containing the info about the message * @return void */ public function export($content) { global $conf; $dsn = $conf->global->SYSLOG_SENTRY_DSN; $client = new Raven_Client($dsn, array('curl_method' => 'exec')); $client->user_context(array('username' => $content['user'] ? $content['user'] : '', 'ip_address' => $content['ip'])); $client->tags_context(array('version' => DOL_VERSION)); $client->registerSeverityMap(array(LOG_EMERG => Raven_Client::FATAL, LOG_ALERT => Raven_Client::FATAL, LOG_CRIT => Raven_Client::ERROR, LOG_ERR => Raven_Client::ERROR, LOG_WARNING => Raven_Client::WARNING, LOG_NOTICE => Raven_Client::WARNING, LOG_INFO => Raven_Client::INFO, LOG_DEBUG => Raven_Client::DEBUG)); if (substr($content['message'], 0, 3) === 'sql') { global $db; $query = substr($content['message'], 4, strlen($content['message'])); $client->captureQuery($query, $client->translateSeverity($content['level']), $db->type); } else { $client->captureMessage($content['message'], null, $client->translateSeverity($content['level'])); } }
/** * @param \Exception $ex * @param array $extra */ public function logException(\Exception $ex, $tags = array(), $extra = array()) { $ravenClient = new \Raven_Client('https://*****:*****@app.getsentry.com/49959'); $tags['php_version'] = phpversion(); $tags['skylab_version'] = \Kunstmaan\Skylab\Application::VERSION; $tags['user'] = posix_getpwuid(posix_geteuid())['name']; $extra = array_merge($extra, $this->app["config"]); if (\Kunstmaan\Skylab\Application::VERSION !== "@package_version@") { $event_id = $ravenClient->getIdent($ravenClient->captureException($ex, array('extra' => $extra, 'tags' => $tags))); $this->output->writeln("\n\n<error> " . $ex->getMessage() . "\n This exception has been reported with id {$event_id}. Please log a github issue at https://github.com/Kunstmaan/skylab/issues and mention this id.</error>\n\n"); } echo $ex->getTraceAsString(); throw $ex; }