binarcode / laravel-developer
轻量级包,用于记录Slack异常。
Requires
- php: ^8.1|^8.2
- ext-json: *
- illuminate/contracts: ^11.0
- laravel/slack-notification-channel: ^3.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.2
- laravel/sanctum: ^4.0
- nunomaduro/larastan: ^2.0
- orchestra/testbench: ^9.0
- phpstan/extension-installer: ^1.1
- phpunit/phpunit: ^10.0|^11.0
- symfony/stopwatch: ^4.4|^5.0
This package is auto-updated.
Last update: 2024-09-24 15:30:23 UTC
README
安装
您可以通过composer安装此包
composer require binarcode/laravel-developer
您可以使用以下命令发布和运行迁移
php artisan vendor:publish --provider="Binarcode\LaravelDeveloper\LaravelDeveloperServiceProvider" --tag="developer-migrations" php artisan migrate
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="Binarcode\LaravelDeveloper\LaravelDeveloperServiceProvider" --tag="developer-config"
这是已发布配置文件的内容
<?php return [ /** * The slack incoming webhook to send notifications. */ 'slack_dev_hook' => env('SLACK_DEV_HOOK'), /** * The url to the web where you may display the exception. * * For instance you can use nova, so the url will look like: /nova/resources/exception-logs/{uuid} * * We will replace the uuid with the exception log uuid. */ 'developer_log_base_url' => env('DEV_developer_log_base_url'), /** * The default notification class used to send notifications. */ 'notification' => \Binarcode\LaravelDeveloper\Notifications\DevNotification::class, ];
此外,您必须为您的Slack工作区创建一个Slack应用。
如果您只需要将通知发送到与App创建在同一Slack工作区中,您应确保您的App具有chat:write
、chat:write.public
和chat:write.customize
作用域。这些作用域可以从Slack中的“OAuth & Permissions”应用管理标签中添加。
使用方法
向Slack发送异常
使用此包的最简单方法是向Slack发送异常
use Binarcode\LaravelDeveloper\LaravelDeveloper; LaravelDeveloper::exceptionToDevSlack( new \Exception('wew') );
或使用助手
slack(new Exception('wew'));
向Slack发送消息
使用此方法向您的开发Slack发送任何消息
use Binarcode\LaravelDeveloper\LaravelDeveloper; LaravelDeveloper::messageToDevSlack('Hey, we have troubles ;-)');
或使用助手
slack('Hey there!');
向Slack发送任何内容
显然,您可以将任何类型的消息发送到Slack频道。`toDevSlack`方法接受一个`DevNotificationDto`实例。
use Binarcode\LaravelDeveloper\LaravelDeveloper; use Binarcode\LaravelDeveloper\Dtos\DevNotificationDto; LaravelDeveloper::toDevSlack( DevNotificationDto::makeWithMessage('hey') );
持久化异常
如果您想将异常持久化到数据库,在任何您想要捕获和记录异常的地方,您可以这样做
use Binarcode\LaravelDeveloper\Models\DeveloperLog; try { // Your custom code } catch (\Throwable $e) { DeveloperLog::makeFromException($e)->save(); }
在内部,此包会在您的数据库的`exception_logs`表中存储异常条目。
或使用助手(但这也将发送Slack通知)
slack($e)->persist()
Slack通知
如果您想将通知发送到Slack webhook,只需在您的`ExceptionLog`实例上调用`notifyDevs()`方法。
这将向您在`developer.slack_dev_hook`配置文件中指定的Slack webhook发送Slack通知。
传递其他有效负载
您可以为异常指定有效负载,这样它就会与异常一起存储。以下示例将捕获一个`Cashier`异常并将其记录下来
use Laravel\Cashier\Exceptions\PaymentFailure; use Binarcode\LaravelDeveloper\Models\DeveloperLog; try { // Your custom code } catch (PaymentFailure $e) { DeveloperLog::makeFromException($e, $e->payment->asStripePaymentIntent())->notifyDevs(); }
第二个`$e->payment->asStripePaymentIntent()`对象必须实现`JsonSerializable`接口。
您可以使用以下方式添加更多有效负载
ExceptionLog::makeFromException($e) ->addPayload($payload1) ->addPayload($payload2) ->notifyDevs();
使用自定义通知
然而,Laravel Developer包提供了`Binarcode\LaravelDeveloper\Notifications\DevNotification`通知,您可以自由地通过配置`developer.notification`来使用一个全新的通知。
'notification': CustomNotification::class,
如果您想完全控制通知发送,您可以在您的某个服务提供者中添加以下内容
use Binarcode\LaravelDeveloper\LaravelDeveloper; use Binarcode\LaravelDeveloper\Notifications\DevNotification; use Illuminate\Support\Facades\Notification; LaravelDeveloper::notifyUsing(function (DevNotification $argument) { // Here you can do anything you want(even send an email), for instance we provide here // an example of how you can send an anonymous notification. Notification::route('slack', config('developer.slack_dev_hook'))->notify( new CustomNotification($argument->notificationDto) ); });
日志修剪
如果不进行修剪,`exception_logs`表可能会非常快速地积累记录。为了缓解这种情况,您应安排`dev:prune` Artisan命令每天运行。
$schedule->command('dev:prune')->daily();
默认情况下,所有超过24小时的条目都将被修剪。您可以在调用命令时使用小时选项来确定保留开发数据的时间长度。例如,以下命令将删除所有超过48小时创建的记录
$schedule->command('dev:prune --hours=48')->daily();
分析
作为开发者,有时您必须测量此类操作的内存使用量或消耗的时间。Laravel Developer可以帮助您做到这一点
measure_memory(function() { // some code });
或
$memory = \Binarcode\LaravelDeveloper\Profiling\ServerMemory::measure(); // some code memory consuming $memory->stop(); $memory->getMemory();
时间测量
measure_timing(function() { // some code })
或
$timing = \Binarcode\LaravelDeveloper\Profiling\ServerTiming::startWithoutKey(); sleep(1); $timing->stopAllUnfinishedEvents(); $timing->getDuration();
开发者身份验证
每个api
都需要进行认证,通过HTTP客户端(例如Postman)进行测试时,我们需要花费大量时间登录用户、复制令牌、将其放入下一个请求中,等等。现在,Laravel开发者提供了一个简单的方法,在local
环境中使用testing
令牌来认证用户。
// app/Http/Kernel.php 'api' => [ //... \Binarcode\LaravelDeveloper\Middleware\DevAuthMiddleware::class, ]
然后将请求的Authorization
头值设置为testing
。
注意:确保DevAuthMiddleware
在api
中间件之前。
自定义解析用户
默认情况下,将从您的配置模型app.providers.users.model
中的第一个条目(通常是用户)使用,但是您可以自定义这一点。
在您的任何服务提供者中,或者在您注入DevAuthMiddleware
的同一位置,您可以提供一个回调,以解析用户实例
use App\Models\User; use Binarcode\LaravelDeveloper\Middleware\DevAuthMiddleware; 'middleware' => [ DevAuthMiddleware::resolveUserUsing(function() { return User::first(); }); 'api', ],
更改Bearer
如果您使用laravel sanctum,并希望显式地使用/生成已解析用户的Bearer,您可以使用\Binarcode\LaravelDeveloper\Middleware\DevAuthMiddleware::class
,它遵循与DevAuthMiddleware
相同的语法。
测试宏
dumpWithoutTrace
如果您在测试中厌烦于每次都向上滚动查看->dump()
响应中的消息,您可以使用->dumpWithoutTrace()
代替,它将返回除长数组以外的所有内容。
代理
我们经常使用常用的Collection
或EnumeratesValues
链方法,但在其他上下文中无法使用这些方法。
when
when
是最有用的方法之一,假设我们有一个这样的类
class DocumentGenerator { public static function make(...$arguments) { return new static(...$arguments); } public function setItem(Item $item): self { $this->item = $item; return $this; } public function setOrder(Order $order): self { $this->order = $order; return $this; } public function generate(){ // } }
您想设置类的顺序和项目,除非它不存在。通常的做法是
$generator = DocumentGenerator::make()->setOrder($order); if ($item) { $generator->setItem($item); } $generator->generate();
使用when
链方法,代码变得更流畅
DocumentGenerator::make() ->setOrder($order) ->when($item, fn($generator) => $generator->setItem($order)) ->generate();
要使其工作,只需添加Binarcode\LaravelDeveloper\Concerns\Proxies
特质
class DocumentGenerator { use Binarcode\LaravelDeveloper\Concerns\Proxies; }
存储日志
有时您可能想要存储简单的日志(例如,当您从应用程序发送一些API请求时,您可能想要存储有效负载)
$payload = [...]; devLog('Called Fedex API with:', $payload)
现在您将在数据库表中有一个条目,包含有效负载和关联的名称。
附加目标
您可以将目标附加到日志中,以便它与模型相关联,如下所示
devLog('Model updated')->target($user);
或者如果您需要附加多个模型,请使用
devLog('Targetable') ->addRelatedModel($user) ->addRelatedModel($post) ->save();
附加元数据
您还可以将元数据附加到日志中
devLog('Targetable') ->addMeta(['browser' => 'safari',]) ->save();
Telescope支持
该软件包将自动将异常存储到telescope中。
只需安装telescope,并将developer.telescope
标记为true
。
Telescope异常将在每个slack($e)->persist()
调用时自动存储,或自定义使用telescopeException($e, 'custom message')
辅助函数。
测试
composer test
变更日志
有关最近更改的更多信息,请参阅CHANGELOG。
贡献
有关详细信息,请参阅CONTRIBUTING。
安全漏洞
请审查我们的安全策略,了解如何报告安全漏洞。
鸣谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。