Skip to content

Commit b03ae4f

Browse files
stayalliveHazAT
authored andcommitted
Do not lazy load Sentry on resolving (#189)
* Do not lazy load Sentry This way the Hub has the current (configured) client and users can use the Hub or SDK methods to configure their environment and/or capture exception with the already configured client. * Update php-cs-fixer to work on PHP 7.3 * Combine Lumen & Laravel service providers * Cleanup the test command * Little cleanups / cs * Stop test command if no DSN was found
1 parent d0ac515 commit b03ae4f

File tree

6 files changed

+75
-196
lines changed

6 files changed

+75
-196
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"phpunit/phpunit": "7.3.*",
2121
"laravel/framework": "5.7.*",
2222
"orchestra/testbench": "3.7.*",
23-
"friendsofphp/php-cs-fixer": "2.7.*"
23+
"friendsofphp/php-cs-fixer": "2.14.*"
2424
},
2525
"autoload": {
2626
"psr-0": {

src/Sentry/Laravel/LogChannel.php

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,7 @@ class LogChannel extends LogManager
1414
*/
1515
public function __invoke(array $config)
1616
{
17-
$handler = new SentryHandler(
18-
$this->app->make('sentry'),
19-
isset($config['level']) ? $config['level'] : null,
20-
isset($config['bubble']) ? $config['bubble'] : true
21-
);
17+
$handler = new SentryHandler($this->app->make('sentry'), $config['level'] ?? null, $config['bubble'] ?? true);
2218

2319
return new Logger($this->parseChannel($config), [$this->prepareHandler($handler, $config)]);
2420
}

src/Sentry/Laravel/LumenServiceProvider.php

Lines changed: 0 additions & 105 deletions
This file was deleted.

src/Sentry/Laravel/ServiceProvider.php

Lines changed: 56 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
namespace Sentry\Laravel;
44

5-
use function Sentry\configureScope;
6-
use Sentry\ClientBuilder;
75
use Sentry\State\Hub;
6+
use Sentry\ClientBuilder;
7+
use Illuminate\Log\LogManager;
8+
use Laravel\Lumen\Application as Lumen;
9+
use Illuminate\Foundation\Application as Laravel;
10+
use Illuminate\Support\ServiceProvider as IlluminateServiceProvider;
811

9-
class ServiceProvider extends \Illuminate\Support\ServiceProvider
12+
class ServiceProvider extends IlluminateServiceProvider
1013
{
1114
/**
1215
* Abstract type to bind Sentry as in the Service Container.
@@ -16,108 +19,102 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider
1619
public static $abstract = 'sentry';
1720

1821
/**
19-
* Bootstrap the application events.
20-
*
21-
* @return void
22+
* Boot the service provider.
2223
*/
23-
public function boot()
24+
public function boot(): void
2425
{
25-
// Publish the configuration file
26-
$this->publishes(array(
27-
__DIR__ . '/../../../config/sentry.php' => config_path(static::$abstract . '.php'),
28-
), 'config');
26+
$this->app->make(self::$abstract);
2927

3028
$this->bindEvents($this->app);
3129

3230
if ($this->app->runningInConsole()) {
31+
if ($this->app instanceof Laravel) {
32+
$this->publishes([
33+
__DIR__ . '/../../../config/sentry.php' => config_path(static::$abstract . '.php'),
34+
], 'config');
35+
}
36+
3337
$this->registerArtisanCommands();
3438
}
3539
}
3640

3741
/**
38-
* Register the artisan commands.
42+
* Register the service provider.
3943
*/
40-
protected function registerArtisanCommands()
44+
public function register(): void
4145
{
42-
$this->commands(array(
43-
'Sentry\Laravel\TestCommand',
44-
));
46+
if ($this->app instanceof Lumen) {
47+
$this->app->configure('sentry');
48+
}
49+
50+
$this->mergeConfigFrom(__DIR__ . '/../../../config/sentry.php', static::$abstract);
51+
52+
$this->configureAndRegisterClient($this->app['config'][static::$abstract]);
53+
54+
if (($logManager = $this->app->make('log')) instanceof LogManager) {
55+
$logManager->extend('sentry', function ($app, array $config) {
56+
return (new LogChannel($app))($config);
57+
});
58+
}
4559
}
4660

4761
/**
4862
* Bind to the Laravel event dispatcher to log events.
49-
*
50-
* @param $app
5163
*/
52-
protected function bindEvents($app)
64+
protected function bindEvents(): void
5365
{
54-
$userConfig = $app['config'][static::$abstract];
66+
$userConfig = $this->app['config'][static::$abstract];
5567

5668
$handler = new EventHandler($userConfig);
5769

58-
$handler->subscribe($app->events);
70+
$handler->subscribe($this->app->events);
5971

60-
// In Laravel >=5.3 we can get the user context from the auth events
61-
if (isset($userConfig['send_default_pii']) && $userConfig['send_default_pii'] !== false && version_compare($app::VERSION, '5.3') >= 0) {
62-
$handler->subscribeAuthEvents($app->events);
72+
if (isset($userConfig['send_default_pii']) && $userConfig['send_default_pii'] !== false) {
73+
$handler->subscribeAuthEvents($this->app->events);
6374
}
6475
}
6576

6677
/**
67-
* Register the service provider.
68-
*
69-
* @return void
78+
* Register the artisan commands.
7079
*/
71-
public function register()
80+
protected function registerArtisanCommands(): void
7281
{
73-
$this->mergeConfigFrom(__DIR__ . '/../../../config/sentry.php', static::$abstract);
74-
75-
$app = $this->app;
82+
$this->commands([
83+
TestCommand::class,
84+
]);
85+
}
7686

77-
$this->app->singleton(static::$abstract, function ($app) {
78-
$userConfig = $app['config'][static::$abstract];
87+
/**
88+
* Configure and register the Sentry client with the container.
89+
*/
90+
protected function configureAndRegisterClient(): void
91+
{
92+
$this->app->singleton(static::$abstract, function () {
7993
$basePath = base_path();
94+
$userConfig = $this->app['config'][static::$abstract];
8095

81-
// We do not want this setting to hit our main client
96+
// We do not want this setting to hit our main client because it's Laravel specific
8297
unset($userConfig['breadcrumbs.sql_bindings']);
98+
8399
$options = \array_merge(
84100
[
85-
'environment' => $app->environment(),
86-
'prefixes' => array($basePath),
101+
'environment' => $this->app->environment(),
102+
'prefixes' => [$basePath],
87103
'project_root' => $basePath,
88-
'in_app_exclude' => array($basePath . '/vendor'),
89-
'integrations' => [new Integration()]
104+
'in_app_exclude' => [$basePath . '/vendor'],
105+
'integrations' => [new Integration],
90106
],
91107
$userConfig
92108
);
109+
93110
$clientBuilder = ClientBuilder::create($options);
94111
$clientBuilder->setSdkIdentifier(Version::SDK_IDENTIFIER);
95112
$clientBuilder->setSdkVersion(Version::SDK_VERSION);
96-
Hub::setCurrent(new Hub($clientBuilder->getClient()));
97113

98-
if (isset($userConfig['send_default_pii']) && $userConfig['send_default_pii'] !== false && version_compare($app::VERSION, '5.3') < 0) {
99-
try {
100-
// Bind user context if available
101-
if ($app['auth']->check()) {
102-
configureScope(function (Scope $scope) use ($app): void {
103-
$scope->setUser(['id' => $app['auth']->user()->getAuthIdentifier()]);
104-
});
105-
}
106-
} catch (Exception $e) {
107-
error_log(sprintf('sentry.breadcrumbs error=%s', $e->getMessage()));
108-
}
109-
}
114+
Hub::setCurrent(new Hub($clientBuilder->getClient()));
110115

111116
return Hub::getCurrent();
112117
});
113-
114-
// Add a sentry log channel for Laravel 5.6+
115-
if (version_compare($app::VERSION, '5.6') >= 0) {
116-
$app->make('log')->extend('sentry', function ($app, array $config) {
117-
$channel = new LogChannel($app);
118-
return $channel($config);
119-
});
120-
}
121118
}
122119

123120
/**

src/Sentry/Laravel/TestCommand.php

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Sentry\Laravel;
44

5+
use Exception;
56
use Illuminate\Console\Command;
67

78
class TestCommand extends Command
@@ -38,34 +39,35 @@ public function handle()
3839
$old_error_reporting = error_reporting(E_ALL | E_STRICT);
3940

4041
try {
42+
/** @var \Sentry\State\Hub $hub */
4143
$hub = app('sentry');
4244

43-
/** @var \Sentry\Client $client */
44-
$client = $hub->getClient();
45-
46-
if ($client->getOptions()->getDsn()) {
47-
$this->info("[sentry] Client DSN discovered!");
45+
if ($hub->getClient()->getOptions()->getDsn()) {
46+
$this->info('[sentry] Client DSN discovered!');
4847
} else {
4948
$this->warn('[sentry] Could not discover DSN! Check your config or .env file');
49+
50+
return;
5051
}
5152

5253
$this->info('[sentry] Generating test event');
5354

54-
$ex = $this->generateTestException('command name', array('foo' => 'bar'));
55+
$ex = $this->generateTestException('command name', ['foo' => 'bar']);
5556

5657
$hub->captureException($ex);
5758

58-
$this->info("[sentry] Sending test event");
59+
$this->info('[sentry] Sending test event');
5960

6061
$lastEventId = $hub->getLastEventId();
62+
6163
if (!$lastEventId) {
62-
$this->error("[sentry] There was an error sending the test event.");
63-
$this->error("[sentry] Please check if you dsn is set properly in your config. SENTRY_LARAVEL_DSN");
64+
$this->error('[sentry] There was an error sending the test event.');
65+
$this->error('[sentry] Please check if you DSN is set properly in your config or .env as `SENTRY_LARAVEL_DSN`.');
6466
} else {
65-
$this->info("[sentry] Event sent: " . $lastEventId);
67+
$this->info("[sentry] Event sent with ID: {$lastEventId}");
6668
}
67-
} catch (\Exception $e) {
68-
$this->error("[sentry] " . $e->getMessage());
69+
} catch (Exception $e) {
70+
$this->error("[sentry] {$e->getMessage()}");
6971
}
7072

7173
error_reporting($old_error_reporting);
@@ -79,12 +81,12 @@ public function handle()
7981
*
8082
* @return \Exception
8183
*/
82-
protected function generateTestException($command, $arg)
84+
protected function generateTestException($command, $arg): ?Exception
8385
{
8486
// Do something silly
8587
try {
86-
throw new \Exception('This is a test exception sent from the Sentry Laravel SDK.');
87-
} catch (\Exception $ex) {
88+
throw new Exception('This is a test exception sent from the Sentry Laravel SDK.');
89+
} catch (Exception $ex) {
8890
return $ex;
8991
}
9092
}

src/Sentry/Laravel/config.php

Lines changed: 0 additions & 11 deletions
This file was deleted.

0 commit comments

Comments
 (0)