Skip to content

Commit

Permalink
Adds sentry
Browse files Browse the repository at this point in the history
  • Loading branch information
huangdijia committed Nov 29, 2022
0 parents commit c4babef
Show file tree
Hide file tree
Showing 22 changed files with 1,453 additions and 0 deletions.
13 changes: 13 additions & 0 deletions .github/workflows/close-pull-request.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
name: Close Pull Request

on:
pull_request_target:
types: [opened]

jobs:
run:
runs-on: ubuntu-latest
steps:
- uses: superbrothers/close-pull-request@v3
with:
comment: "Thank you for your pull request. However, you have submitted this PR on the friendsofhyperf organization which is a read-only sub split of `friendsofhyperf/components`. Please submit your PR on the https://github.com/friendsofhyperf/components repository.<br><br>Thanks!"
25 changes: 25 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
on:
push:
# Sequence of patterns matched against refs/tags
tags:
- 'v*' # Push events to matching v*, i.e. v1.0, v1.0.0

name: Release

jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 D.J.Hwang

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# Sentry

[![Latest Test](https://github.com/friendsofhyperf/sentry/workflows/tests/badge.svg)](https://github.com/friendsofhyperf/sentry/actions)
[![Latest Version on Packagist](https://img.shields.io/packagist/v/friendsofhyperf/sentry.svg?style=flat-square)](https://packagist.org/packages/friendsofhyperf/sentry)
[![Total Downloads](https://img.shields.io/packagist/dt/friendsofhyperf/sentry.svg?style=flat-square)](https://packagist.org/packages/friendsofhyperf/sentry)
[![GitHub license](https://img.shields.io/github/license/friendsofhyperf/sentry)](https://github.com/friendsofhyperf/sentry)

## Installation

```shell
composer require friendsofhyperf/sentry
```

## Publish config file

```shell
php bin/hyperf.php vendor:publish friendsofhyperf/sentry
```

## Register exception handler

```php
return [
'handler' => [
'http' => [
FriendsOfHyperf\Sentry\SentryExceptionHandler::class,
App\Exception\Handler\AppExceptionHandler::class,
],
],
];
```

## Register logger handler

```php
<?php

return [
// ...
'sentry' => [
'handler' => [
'class' => FriendsOfHyperf\Sentry\SentryHandler::class,
'constructor' => [
'level' => \Monolog\Logger::DEBUG,
],
],
'formatter' => [
'class' => \Monolog\Formatter\LineFormatter::class,
'constructor' => [
'format' => null,
'dateFormat' => null,
'allowInlineLineBreaks' => true,
]
],
],
// ...
];

```
61 changes: 61 additions & 0 deletions class_map/SentrySdk.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);
/**
* This file is part of friendsofhyperf/sentry.
*
* @link https://github.com/friendsofhyperf/sentry
* @document https://github.com/friendsofhyperf/sentry/blob/main/README.md
* @contact [email protected]
*/
namespace Sentry;

use Hyperf\Context\Context;
use Sentry\State\Hub;
use Sentry\State\HubInterface;

/**
* @see \Sentry\SentrySdk
*/
class SentrySdk
{
/**
* @var null|HubInterface The current hub
*/
private static $currentHub;

/**
* Constructor.
*/
private function __construct()
{
}

/**
* Initializes the SDK by creating a new hub instance each time this method
* gets called.
*/
public static function init(): HubInterface
{
return tap(new Hub(), fn ($hub) => Context::set(__CLASS__, $hub));
}

/**
* Gets the current hub. If it's not initialized then creates a new instance
* and sets it as current hub.
*/
public static function getCurrentHub(): HubInterface
{
return Context::getOrSet(__CLASS__, fn () => new Hub());
}

/**
* Sets the current hub.
*
* @param HubInterface $hub The hub to set
*/
public static function setCurrentHub(HubInterface $hub): HubInterface
{
return tap($hub, fn ($hub) => Context::set(__CLASS__, $hub));
}
}
35 changes: 35 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "friendsofhyperf/sentry",
"description": "The sentry component for Hyperf.",
"type": "library",
"license": "MIT",
"keywords": [
"php",
"hyperf",
"sentry"
],
"autoload": {
"psr-4": {
"FriendsOfHyperf\\Sentry\\": "src/"
}
},
"require": {
"hyperf/command": "~3.0.0",
"hyperf/database": "~3.0.0",
"hyperf/di": "~3.0.0",
"hyperf/event": "~3.0.0",
"hyperf/exception-handler": "~3.0.0",
"hyperf/framework": "~3.0.0",
"hyperf/logger": "~3.0.0",
"sentry/sdk": "^3.0"
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"extra": {
"hyperf": {
"config": "FriendsOfHyperf\\Sentry\\ConfigProvider"
}
}
}
32 changes: 32 additions & 0 deletions publish/sentry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);
/**
* This file is part of friendsofhyperf/sentry.
*
* @link https://github.com/friendsofhyperf/sentry
* @document https://github.com/friendsofhyperf/sentry/blob/main/README.md
* @contact [email protected]
*/
return [
'dsn' => env('SENTRY_DSN', ''),

// capture release as git sha
// 'release' => trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD')),

'environment' => env('APP_ENV'),

// @see: https://docs.sentry.io/platforms/php/configuration/options/#send-default-pii
'send_default_pii' => false,

'breadcrumbs' => [
'sql_queries' => true,
'sql_bindings' => true,
'sql_transaction' => true,
'redis' => true,
'guzzle' => true,
'logs' => true,
],

'integrations' => [],
];
60 changes: 60 additions & 0 deletions src/Aspect/HttpClientAspect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);
/**
* This file is part of friendsofhyperf/sentry.
*
* @link https://github.com/friendsofhyperf/sentry
* @document https://github.com/friendsofhyperf/sentry/blob/main/README.md
* @contact [email protected]
*/
namespace FriendsOfHyperf\Sentry\Aspect;

use FriendsOfHyperf\Sentry\Integration;
use GuzzleHttp\Client;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Aop\AroundInterface;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Sentry\Breadcrumb;

class HttpClientAspect implements AroundInterface
{
public array $classes = [
Client::class . '::requestAsync',
];

public function __construct(protected ConfigInterface $config)
{
}

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
$startTime = microtime(true);
$arguments = $proceedingJoinPoint->arguments;
$options = $proceedingJoinPoint->arguments['keys']['options'];

return tap($proceedingJoinPoint->process(), function ($result) use ($arguments, $options, $startTime) {
if (! $this->config->get('sentry.breadcrumbs.guzzle', false)) {
return;
}

if (isset($options['no_aspect']) && $options['no_aspect'] === true) {
return;
}

$uri = $arguments['keys']['uri'] ?? '';
$data['request']['method'] = $options['method'] ?? 'GET';
$data['request']['headers'] = $options['headers'] ?? [];
$data['request']['query'] = $options['query'] ?? [];
$data['timeMs'] = (microtime(true) - $startTime) * 1000;

Integration::addBreadcrumb(new Breadcrumb(
Breadcrumb::LEVEL_INFO,
Breadcrumb::TYPE_DEFAULT,
'guzzle',
$uri,
$data
));
});
}
}
76 changes: 76 additions & 0 deletions src/Aspect/LoggerAspect.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);
/**
* This file is part of friendsofhyperf/sentry.
*
* @link https://github.com/friendsofhyperf/sentry
* @document https://github.com/friendsofhyperf/sentry/blob/main/README.md
* @contact [email protected]
*/
namespace FriendsOfHyperf\Sentry\Aspect;

use FriendsOfHyperf\Sentry\Integration;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Aop\AbstractAspect;
use Hyperf\Di\Aop\ProceedingJoinPoint;
use Monolog\DateTimeImmutable;
use Monolog\Logger;
use Sentry\Breadcrumb;
use Sentry\Severity;
use UnitEnum;

class LoggerAspect extends AbstractAspect
{
public array $classes = [
Logger::class . '::addRecord',
];

public function __construct(protected ConfigInterface $config)
{
}

public function process(ProceedingJoinPoint $proceedingJoinPoint)
{
return tap($proceedingJoinPoint->process(), function ($result) use ($proceedingJoinPoint) {
if (! $this->config->get('sentry.breadcrumbs.logs', false)) {
return;
}

$level = $proceedingJoinPoint->arguments['keys']['level'];
$level = $level instanceof UnitEnum ? (int) $level->value : (int) $level;
$message = $proceedingJoinPoint->arguments['keys']['message'];
$context = $proceedingJoinPoint->arguments['keys']['context'];
/** @var null|DateTimeImmutable $datetime */
$datetime = $proceedingJoinPoint->arguments['keys']['datetime'];

if (isset($context['no_aspect']) && $context['no_aspect'] === true) {
return;
}

Integration::addBreadcrumb(new Breadcrumb(
(string) $this->getLogLevel($level),
Breadcrumb::TYPE_DEFAULT,
'log.' . Logger::getLevelName($level),
$message,
$context,
$datetime?->getTimestamp()
));
});
}

/**
* Translates Monolog log levels to Sentry Severity.
*/
protected function getLogLevel(int $logLevel): Severity
{
return match ($logLevel) {
Logger::DEBUG => Severity::debug(),
Logger::NOTICE, Logger::INFO => Severity::info(),
Logger::WARNING => Severity::warning(),
Logger::ALERT, Logger::EMERGENCY, Logger::CRITICAL => Severity::fatal(),
Logger::ERROR => Severity::error(),
default => Severity::error(),
};
}
}
Loading

0 comments on commit c4babef

Please sign in to comment.