Skip to content

Commit

Permalink
Merge pull request #20 from o0h/2.x
Browse files Browse the repository at this point in the history
Ready to release 2.0.0
  • Loading branch information
o0h authored Nov 23, 2019
2 parents 1c0234e + 9dfc71c commit 2638426
Show file tree
Hide file tree
Showing 91 changed files with 5,034 additions and 241 deletions.
8 changes: 8 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.gitattributes export-ignore
.gitignore export-ignore
.travis.yml export-ignore
README.md
phpcs.xml export-ignore
phpstan.neon export-ignore
phpunit.xml export-ignore
tests export-ignore
30 changes: 24 additions & 6 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
language: php
php:
- 7.0
- 7.1
- 7.2
- 7.3
Expand All @@ -10,13 +9,32 @@ cache:
- vendor
- $HOME/.composer/cache

env:
global:
- PREFER_LOWEST="--prefer-lowest" TEST=1 CODECOV=0 STAN=0

matrix:
include:
- php: 7.3
env: PREFER_LOWEST="" TEST=1 CODECOV=1 STAN=1
- php: "7.4snapshot"
env: PREFER_LOWEST="" TEST=1 CODECOV=0 STAN=0

before_script:
- composer install --prefer-dist --no-interaction
- if [[ $TRAVIS_PHP_VERSION != '7.4snapshot' ]]; then phpenv config-rm xdebug.ini; fi
# @see https://github.com/cakephp/cakephp/commit/249cbc3d3a00e9eca931f44ee6990312f156e6cc#diff-4dafde5c48406484f186b8294c20e12c
- if [[ $TRAVIS_PHP_VERSION = 7.3 && $PREFER_LOWEST = '--prefer-lowest' ]]; then composer require cakephp/cakephp:3.6.13; fi
- composer update --prefer-dist --no-interaction $PREFER_LOWEST
- composer show -i

script:
- composer cs-check
- vendor/bin/phpunit --coverage-clover=clover.xml
- vendor/bin/phpstan analyse src -l 2
- if [[ $TEST = 1 && $CODECOV = 0 ]]; then vendor/bin/phpunit; fi
- if [[ $TEST = 1 && $CODECOV = 1 ]]; then phpdbg -qrr vendor/bin/phpunit --coverage-clover=clover.xml; fi
- |
if [[ $STAN = 1 ]]; then
composer cs-check
vendor/bin/phpstan analyse
fi
after_success:
- bash <(curl -s https://codecov.io/bash)
- if [[ $TEST = 1 && $CODECOV = 1 ]]; then bash <(curl -s https://codecov.io/bash); fi
148 changes: 99 additions & 49 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
# CakePHP Sentry Plugin
CakePHP integration for Sentry.

[![Latest Stable Version](https://poser.pugx.org/connehito/cake-sentry/v/stable)](https://packagist.org/packages/connehito/cake-sentry)
[![Total Downloads](https://poser.pugx.org/connehito/cake-sentry/downloads)](https://packagist.org/packages/connehito/cake-sentry)
[![Build Status](https://travis-ci.org/Connehito/cake-sentry.svg?branch=master)](https://travis-ci.org/Connehito/cake-sentry)
[![codecov](https://codecov.io/gh/connehito/cake-sentry/branch/master/graph/badge.svg)](https://codecov.io/gh/connehito/cake-sentry)
[![MIT License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://github.com/Connehito/cake-sentry/blob/master/LICENSE)
[![License](https://poser.pugx.org/connehito/cake-sentry/license)](https://packagist.org/packages/connehito/cake-sentry)

## Requirements
- PHP 7.0+
- CakePHP 3.5+
- PHP 7.1+
- CakePHP 3.6+
- and [Sentry](https://sentry.io) account


Expand All @@ -20,20 +22,28 @@ composer require connehito/cake-sentry
## Usage

### Set config files.
in `config/bootstrap.php`
```php
Plugin::load('Connehito/CakeSentry', ['bootstrap' => true]);
```

Write your sentry account info.
```php
// in `config/app.php`
return [
'Sentry' => [
'dsn' => YOUR_SENTRY_DSN_HERE
]
];
```

or use cake command.
### Loading plugin.
In Application.php
```php
public function bootstrap()
{
parent::bootstrap();

$this->addPlugin(\Connehito\CakeSentry\Plugin::class);
}
```

Or use cake command.
```
bin/cake plugin load Connehito/CakeSentry --bootstrap
```
Expand All @@ -44,7 +54,7 @@ That's all! :tada:

#### Ignore noisy exceptions
You can filter out exceptions that make a fuss and harder to determine the issues to address(like PageNotFoundException)
Set exceptions not to log in `Error.skipLog`.
Set exceptions not to log in `Error.skipLog`.

ex)
```php
Expand All @@ -61,11 +71,51 @@ ex)
ref: CakePHP Cookbook
https://book.cakephp.org/3.0/en/development/errors.html#error-exception-configuration

#### Send more context
Client dispatch `CakeSentry.Client.beforeCapture` event before sending error to sentry.
You can set context with EventListener.Calling Raven_Client's API or returning values, error context will be sent. The Returned values will be passed to `Raven_Client::captureMessage()` 3rd arguments(Additional attributes to pass with this event).
### Set Options
All configure written in `Configure::write('Sentry')` will be passed to `Sentry\init()`.
Please check Sentry's official document [about configuration](https://docs.sentry.io/error-reporting/configuration/?platform=php) and [about php-sdk's configuraion](https://docs.sentry.io/platforms/php/#php-specific-options).

In addition to it, CakeSentry provides event hook to set dynamic values to options more easily if you need.
Client dispatch `CakeSentry.Client.afterSetup` event before sending error to sentry.
Subscribe the event with your logic.

ex)
```php
use Cake\Event\Event;
use Cake\Event\EventListenerInterface;

class SentryOptionsContext implements EventListenerInterface
{
public function implementedEvents()
{
return [
'CakeSentry.Client.afterSetup' => 'setServerContext',
];
}

public function setServerContext(Event $event)
{
/** @var Client $subject */
$subject = $event->getSubject();
$options = $subject->getHub()->getClient()->getOptions();

$options->setEnvironment('test_app');
$options->setRelease('2.0.0@dev');
}
}
```

And in `config/bootstrap.php`
```php
EventManager::instance()->on(new SentryOptionsContext());
```

### Send more context

Client dispatch `CakeSentry.Client.beforeCapture` event before sending error to sentry.
You can set context with EventListener.With facade `sentryConfigureScope()` etc, or with `$event->getContext()->getHub()` to access and set context.Calling Raven_Client's API or returning values, error context will be sent.
Now, cake-sentry supports to get `Request` instance in implemented event via `$event->getSubject()->getRequest()`.
See also [the section about context in offical doc](https://docs.sentry.io/enriching-error-data/context/?platform=php).

ex)
```php
Expand All @@ -83,21 +133,25 @@ class SentryErrorContext implements EventListenerInterface

public function setContext(Event $event)
{
$request = $event->getSubject()->getRequest();
$request->trustProxy = true;
$raven = $event->getSubject()->getRaven();
$raven->user_context([
'ip_address' => $request->clientIp()
]);
$raven->tags_context([
'app_version' => $request->getHeaderLine('App-Version') ?: 1.0,
]);

return [
'extra' => [
'foo' => 'bar',
]
];
if (PHP_SAPI !== 'cli') {
/** @var ServerRequest $request */
$request = $event->getData('request') ?? ServerRequestFactory::fromGlobals();
$request->trustProxy = true;

sentryConfigureScope(function (Scope $scope) use ($request, $event) {
$scope->setTag('app_version', $request->getHeaderLine('App-Version') ?: 1.0);
$exception = $event->getData('exception');
if ($exception) {
assert($exception instanceof \Exception);
$scope->setTag('status', $exception->getCode());
}
$scope->setUser(['ip_address' => $request->clientIp()]);
$scope->setExtras([
'foo' => 'bar',
'request attributes' => $request->getAttributes(),
]);
});
}
}
}
```
Expand All @@ -107,31 +161,27 @@ And in `config/bootstrap.php`
EventManager::instance()->on(new SentryErrorContext());
```

ref: Sentry official PHP SDK document.
https://docs.sentry.io/clients/php/

#### Register send callback
The plugin allows you to inject `send_callback` option to Raven client.
It will be called in after client send data to Sentry.
See also [offcial doc](https://docs.sentry.io/clients/php/config/).
### Collecting User feedback
In `CakeSentry.Client.afterCapture` event, you can get last event ID.
See also [offcial doc](https://docs.sentry.io/enriching-error-data/user-feedback/?platform=php#collecting-feedback).

ex)
```php
// In app.php, setup callback closure for receiving event id from Raven.
// This sample enables you to get "Event ID" via `$Session` in your controller.
// cf) https://docs.sentry.io/learn/user-feedback/
'Sentry' => [
'dsn' => env('SENTRY_DSN'),
'options' => [
'send_callback' => function ($data) {
$request = \Cake\Http\ServerRequestFactory::fromGlobals();
$session = $request->getSession();
$session->write('last_event_id', $data['event_id']);
}
],
],
```
class SentryErrorContext implements EventListenerInterface
{
public function implementedEvents()
{
return [
'CakeSentry.Client.afterCapture' => 'callbackAfterCapture',
];
}

public function callbackAfterCapture(Event $event)
{
$lastEventId = $event->getData('lastEventId');
}
}
```

## Contributing
Pull requests and feedback are very welcome :)
Expand Down
18 changes: 11 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
"description": "Sentry plugin for CakePHP3",
"type": "cakephp-plugin",
"require": {
"php": "^7.0",
"cakephp/cakephp": "~3.5",
"sentry/sentry": "^1.7"
"php": "^7.1",
"cakephp/cakephp": "^3.6",
"sentry/sdk": "^2.0",
"sentry/sentry": "^2.2"
},
"require-dev": {
"cakephp/cakephp-codesniffer": "^3.0",
"dereuromark/cakephp-ide-helper": "^0.10.3",
"phpunit/phpunit": "^6.4",
"phpstan/phpstan": "^0.9.2"
"jangregor/phpstan-prophecy": "^0.4.2",
"phpstan/phpstan": "@stable",
"phpunit/phpunit": "^6.4|^7.0"
},
"license": "MIT",
"autoload": {
Expand All @@ -28,10 +29,13 @@
"test": "phpunit",
"cs-check": "phpcs --colors -p ./src"
},
"config": {
"sort-packages": true
},
"authors": [
{
"name": "Hideki Kinjyo",
"email": "kinjyo@connehito.com",
"email": "dev@o0h.in",
"role": "Maintainer"
}
]
Expand Down
20 changes: 3 additions & 17 deletions config/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@
namespace Connehito\CakeSentry;

use Cake\Core\Configure;
use Cake\Error\Middleware\ErrorHandlerMiddleware as CakeErrorHandlerMiddleware;
use Cake\Event\EventManager;
use Cake\Log\Log;
use Connehito\CakeSentry\Error\ConsoleErrorHandler;
use Connehito\CakeSentry\Error\ErrorHandler;
use Connehito\CakeSentry\Error\Middleware\ErrorHandlerMiddleware;
use Connehito\CakeSentry\Log\Engine\SentryLog;
use LogicException;

$isCli = PHP_SAPI === 'cli';
if (!$isCli && strpos((env('argv')[0] ?? ''), '/phpunit') !== false) {
$isCli = true;
}
if ($isCli) {
(new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
Expand All @@ -22,16 +21,3 @@
$errorLogConfig['className'] = SentryLog::class;
Log::drop('error');
Log::setConfig('error', $errorLogConfig);

$appClass = Configure::read('App.namespace') . '\Application';
if (class_exists($appClass)) {
EventManager::instance()->on('Server.buildMiddleware', function ($event, $queue) {
/* @var \Cake\Http\MiddlewareQueue $queue */
$middleware = new ErrorHandlerMiddleware();
try {
$queue->insertAfter(CakeErrorHandlerMiddleware::class, $middleware);
} catch (LogicException $e) {
$queue->prepend($middleware);
}
});
}
10 changes: 10 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
includes:
- vendor/jangregor/phpstan-prophecy/src/extension.neon
parameters:
paths:
- src
- tests/TestCase
level: 5
autoload_files:
- tests/bootstrap.php
- tests/TestCase/Error/SentryErrorHandlerTraitTest.php # for including stub class
1 change: 0 additions & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
colors="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
bootstrap="./tests/bootstrap.php"
backupGlobals="true"
>
Expand Down
Loading

0 comments on commit 2638426

Please sign in to comment.