请求添加tag
laravel开了telescope,请求添加tag还好说
//直接在TelescopeServiceProvider的register方法判断就好了
Telescope::tag(function (IncomingEntry $entry) {
if ($entry->isRequest()){
$tags = [];
$tags[] = preg_replace('/(\d+)\.(\d+)\.(\d+)\.(\d+)/', '$1.$2.*.*', request()->getClientIp());
$tags[] = preg_replace('/(\d+)\.(\d+)\.(\d+)\.(\d+)/', '$1.$2.$3.*', request()->getClientIp());
$tags[] = $t;
if (! request()->header('referer') ) {
$tags[] = 'noreferer';
}
return $tags;
}
});
job添加tag
想给job添加tag,而且需要根据job的数据添加tag,直接在job方法中新增一个tags方法即可
<?php
namespace App\Jobs;
class XXJob implements ShouldQueue, ShouldBeUnique {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $id;
public function __construct($id)
{
$this->id = $id;
}
public function uniqueId()
{
return $this->id;
}
public function handle()
{
//....
}
public function retryUntil()
{
return now()->addDays(3);
}
public function tags()
{
return ['job-tags', 'job-tags:' . $this->id];
}
}
看看源码
class JobWatcher extends Watcher
{
//1. 注册监听器 callback
public function register($app)
{
Queue::createPayloadUsing(function ($connection, $queue, $payload) {
return ['telescope_uuid' => optional($this->recordJob($connection, $queue, $payload))->uuid];
});
$app['events']->listen(JobProcessed::class, [$this, 'recordProcessedJob']);
$app['events']->listen(JobFailed::class, [$this, 'recordFailedJob']);
}
public function recordJob($connection, $queue, array $payload)
{
if (! Telescope::isRecording()) {
return;
}
$content = array_merge([
'status' => 'pending',
], $this->defaultJobData($connection, $queue, $payload, $this->data($payload)));
//2. 设置tag
Telescope::recordJob(
$entry = IncomingEntry::make($content)
->withFamilyHash($content['data']['batchId'] ?? null)
->tags($this->tags($payload))
);
return $entry;
}
//3. 这里的payload是 telescope job页面的 Job Details ,$payload['data'] 就是Data栏
protected function tags(array $payload)
{
if (! isset($payload['data']['command'])) {
return [];
}
return ExtractTags::fromJob(
$payload['data']['command']
);
}
}
class ExtractTags
{
public static function fromJob($job)
{
if ($tags = static::extractExplicitTags($job)) {
return $tags;
}
//5. 当job不存在tags方法时
return static::modelsFor(static::targetsFor($job))->map(function ($model) {
return FormatModel::given($model);
})->all();
}
protected static function extractExplicitTags($job)
{
return $job instanceof CallQueuedListener
? static::tagsForListener($job)
: static::explicitTags(static::targetsFor($job));
}
//4. 判断job是否存在tags方法,如果有就调用,不然就返回空数组
protected static function explicitTags(array $targets)
{
return collect($targets)->map(function ($target) {
return method_exists($target, 'tags') ? $target->tags() : [];
})->collapse()->unique()->all();
}
}
class FormatModel
{
//6. 默认的modename:modelid
public static function given($model)
{
return get_class($model).':'.implode('_', Arr::wrap($model->getKey()));
}
}