Skip to content

Commit

Permalink
Add exception handler.
Browse files Browse the repository at this point in the history
  • Loading branch information
elaman committed Jul 14, 2024
1 parent 3799feb commit 899cc3b
Show file tree
Hide file tree
Showing 8 changed files with 200 additions and 132 deletions.
5 changes: 1 addition & 4 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ root = true
[*]
end_of_line = LF
indent_style = space
indent_size = 4
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[{*.yml,*yaml}]
indent_size = 2
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ composer.lock
.bash_history
/.phpunit.result.cache
.DS_Store
/.idea
14 changes: 14 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# simplesamlphp-module-rollbar changelog
All notable changes to simplesamlphp-module-rollbar will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [unreleased]
-

## [v1.0.1]
- Add exception handling as an alternative to logger.

## [v1.0.0]
- Initial release.
24 changes: 17 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,26 @@

SimpleSAMLphp + Rollbar

### simpleSAMLphp module
### SimpleSAMLphp module

This module for SimpleSAMLphp provides a LoggerHandler that integrates with Rollbar service.

## Installation

1. Install simpleSAMLphp.
3. Install rollbar - `composer require systemseed/simplesamlphp-module-rollbar`.
4. Set `rollbar.token` value in `simplesamlphp/config/config.php`.
4. Set `rollbar.environment` value in `simplesamlphp/config/config.php`.
5. Set `logging.handler` to `'SimpleSAML\Module\rollbar\Logger\RollbarLoggingHandler'`.
6. Optionally set `logging.level` to `SimpleSAML\Logger::ERR` to send only errors.
- Install and configure SimpleSAMLphp.
- Install Rollbar - `composer require systemseed/simplesamlphp-module-rollbar`.

## Enable Rollbar

- Fill `rollbar.token` value in `simplesamlphp/config/config.php` with server token taken from Rollbar.
- Set `rollbar.environment` value in `simplesamlphp/config/config.php` to define current environment name.

### Configure Rollbar to handle PHP exceptions

Set `rollbar.exception_handler` value to `true` in `simplesamlphp/config/config.php`. This will catch and log all
exceptions to Rollbar as a single occurrence in Rollbar dashboard.

### Configure Rollbar to handle all log items

Set `logging.handler` to `'SimpleSAML\Module\rollbar\Logger\RollbarLoggingHandler'`. Please be aware that enabled
backtraces, will result in each line in the backtrace treated as a separate occurrence.
8 changes: 5 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,16 @@
"simplesamlphp/composer-module-installer": "~1.0"
},
"require-dev": {
"squizlabs/php_codesniffer": "^3.0"
"squizlabs/php_codesniffer": "^3.0",
"drupal/coder": "8.3.13"
},
"autoload-dev": {
"classmap": ["src/", "tests/"]
"classmap": ["src/"]
},
"config": {
"allow-plugins": {
"simplesamlphp/composer-module-installer": true
"simplesamlphp/composer-module-installer": true,
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
}
40 changes: 40 additions & 0 deletions hooks/hook_exception_handler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

/**
* @file
* Utilize hook provided by SimpleSAMLphp to log PHP exceptions.
* @see https://simplesamlphp.org/docs/stable/simplesamlphp-modules.html#hook-interface
*/

declare(strict_types=1);

use Rollbar\Payload\Level;
use Rollbar\Rollbar;
use SimpleSAML\Configuration;

/**
* Hook to run a cron job.
*
* @param Throwable $exception
* The exception.
*
* @throws Throwable
*/
function rollbar_hook_exception_handler(Throwable $exception): void {
// Check if Rollbar is configured to handle exceptions.
$config = Configuration::getConfig();
$enabled = $config->getOptionalBoolean('rollbar.exception_handler', FALSE);
$token = $config->getOptionalString('rollbar.token', '');
$environment = $config->getOptionalString('rollbar.environment', '');

if ($enabled && $token && $environment) {
// Initialize and configure the logger.
Rollbar::init([
'access_token' => $token,
'environment' => $environment,
], FALSE, FALSE, FALSE);

// Log the exception.
Rollbar::logger()->report(Level::ERROR, $exception, isUncaught: TRUE);
}
}
19 changes: 13 additions & 6 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
<?xml version="1.0"?>
<ruleset name="rollbar">
<description>The coding standard for rollbar.</description>
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="phpcs-standard">
<description>Drupal based codestyle ruleset</description>

<rule ref="PSR12" />
<file>./src</file>
<file>./public</file>
<!-- Specify standards. -->
<rule ref="Drupal"/>
<rule ref="DrupalPractice"/>

<!-- Include path with the Drupal and DrupalPractice rules. -->
<config name="installed_paths" value="vendor/drupal/coder/coder_sniffer"/>

<!-- Specify folders. -->
<file>./hooks</file>
<file>./src</file>
</ruleset>
221 changes: 109 additions & 112 deletions src/Logger/RollbarLoggingHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,123 +13,120 @@
*
* @package SimpleSAMLphp
*/
class RollbarLoggingHandler implements LoggingHandlerInterface
{
/**
* Checks if the Rollbar is initialized.
*
* @var bool
*/
private $isInitialized = false;

/**
* This array contains the mappings from syslog log level to names.
*
* @var array<int, string>
*/
private static array $levelMap = [
Logger::EMERG => RollbarLogLevel::EMERGENCY,
Logger::ALERT => RollbarLogLevel::ALERT,
Logger::CRIT => RollbarLogLevel::CRITICAL,
Logger::ERR => RollbarLogLevel::ERROR,
Logger::WARNING => RollbarLogLevel::WARNING,
Logger::NOTICE => RollbarLogLevel::NOTICE,
Logger::INFO => RollbarLogLevel::INFO,
Logger::DEBUG => RollbarLogLevel::DEBUG,
];

/**
* The name of this process.
*
* @var string
*/
private string $processname;

/**
* The Rollbar API token.
*
* @var string
*/
private string $token;

/**
* The name of this envrionment.
*
* @var string
*/
private string $environment;


/**
* ErrorLogLoggingHandler constructor.
*
* @param \SimpleSAML\Configuration $config The configuration object for this handler.
*/
public function __construct(Configuration $config)
{
// Remove any non-printable characters before storing
$this->processname = preg_replace(
'/[\x00-\x1F\x7F\xA0]/u',
'',
$config->getOptionalString('logging.processname', 'SimpleSAMLphp')
);

// Rollbar related configs.
$this->token = $config->getOptionalString('rollbar.token', '');
$this->environment = $config->getOptionalString('rollbar.environment', '');
class RollbarLoggingHandler implements LoggingHandlerInterface {
/**
* Checks if the Rollbar is initialized.
*
* @var bool
*/
private $isInitialized = FALSE;

/**
* This array contains the mappings from syslog log level to names.
*
* @var arrayintstring
*/
private static array $levelMap = [
Logger::EMERG => RollbarLogLevel::EMERGENCY,
Logger::ALERT => RollbarLogLevel::ALERT,
Logger::CRIT => RollbarLogLevel::CRITICAL,
Logger::ERR => RollbarLogLevel::ERROR,
Logger::WARNING => RollbarLogLevel::WARNING,
Logger::NOTICE => RollbarLogLevel::NOTICE,
Logger::INFO => RollbarLogLevel::INFO,
Logger::DEBUG => RollbarLogLevel::DEBUG,
];

/**
* The name of this process.
*
* @var string
*/
private string $processname;

/**
* The Rollbar API token.
*
* @var string
*/
private string $token;

/**
* The name of this envrionment.
*
* @var string
*/
private string $environment;

/**
* ErrorLogLoggingHandler constructor.
*
* @param \SimpleSAML\Configuration $config
* The configuration object for this handler.
*/
public function __construct(Configuration $config) {
// Remove any non-printable characters before storing.
$this->processname = preg_replace(
'/[\x00-\x1F\x7F\xA0]/u',
'',
$config->getOptionalString('logging.processname', 'SimpleSAMLphp')
);

// Rollbar related configs.
$this->token = $config->getOptionalString('rollbar.token', '');
$this->environment = $config->getOptionalString('rollbar.environment', '');
}

/**
* Initialize rollbar object.
*/
protected function init() {
if (empty($this->token) || empty($this->environment)) {
return FALSE;
}

/**
* Initialize rollbar object.
*/
protected function init()
{
if (empty($this->token) || empty($this->environment)) {
return false;
}

if (!$this->isInitialized) {
Rollbar::init([
'access_token' => $this->token,
'environment' => $this->environment,
]);
$this->isInitialized = true;
}

return true;
if (!$this->isInitialized) {
Rollbar::init([
'access_token' => $this->token,
'environment' => $this->environment,
]);
$this->isInitialized = TRUE;
}


/**
* Set the format desired for the logs.
*
* @param string $format The format used for logs.
*/
public function setLogFormat(string $format): void
{
// we don't need the format here
return TRUE;
}

/**
* Set the format desired for the logs.
*
* @param string $format
* The format used for logs.
*/
public function setLogFormat(string $format): void {
// We don't need the format here.
}

/**
* Log a message to syslog.
*
* @param int $level
* The log level.
* @param string $string
* The formatted message to log.
*/
public function log(int $level, string $string): void {
$levelName = self::$levelMap[$level] ?? sprintf('UNKNOWN%d', $level);
if (!$this->init()) {
return;
}

$formats = ['%process', '%level'];
$replacements = [$this->processname, strtoupper($levelName)];
$string = str_replace($formats, $replacements, $string);
$string = preg_replace('/^%date(\{[^\}]+\})?\s*/', '', $string);
$string = trim($string);

Rollbar::log($levelName, $string);
}

/**
* Log a message to syslog.
*
* @param int $level The log level.
* @param string $string The formatted message to log.
*/
public function log(int $level, string $string): void
{
$levelName = self::$levelMap[$level] ?? sprintf('UNKNOWN%d', $level);
if (!$this->init()) {
return;
}

$formats = ['%process', '%level'];
$replacements = [$this->processname, strtoupper($levelName)];
$string = str_replace($formats, $replacements, $string);
$string = preg_replace('/^%date(\{[^\}]+\})?\s*/', '', $string);
$string = trim($string);

Rollbar::log($levelName, $string);
}
}

0 comments on commit 899cc3b

Please sign in to comment.