讨论数量:
我们是写在 AppServiceProvider
里面,注册个挂钟实例,主要就看 API 或者 队里里面执行各个位置的时间。
$this->app->instance('wallTime', new WallTime());
Queue::before(function (JobProcessing $event) {
$this->app->instance('wallTime', new WallTime());
});
缺点嘛,就是没法去统计服务注册的耗时(如果加载的提供者注册方法写的不局气,还是有很大风险的)。
WallTime逻辑比较简单就是打日志:
<?php
namespace App\Services;
use Illuminate\Support\Str;
class WallTime
{
/**
* 默认标记长度
*/
const MARK_LENGTH_DEFAULT = 6;
/**
* 慢日志默认超时时间
*/
const SLOW_LOG_TIMEOUT_DEFAULT = 3;
/**
* @var float 挂钟时间
*/
protected $wallTime;
/**
* @var string 标识
*/
protected $mark;
/**
* @var array 日志数据
*/
protected $log = [];
/**
* 构造函数
*
* @param int $markLength
*/
public function __construct(int $markLength = self::MARK_LENGTH_DEFAULT)
{
$this->wallTime = microtime(true);
$this->mark = Str::random($markLength);
}
/**
* 经过时间
*
* @return float
*/
public function delay(): float
{
return round(microtime(true)-$this->wallTime,2);
}
/**
* 获取标识
*
* @return string
*/
public function mark(): string
{
return $this->mark;
}
/**
* 记录日志
*
* @param array $data
*/
public function info(array $data = [])
{
info($this->message(), $data);
}
/**
* 慢日志
*
* @param array $data
* @param int $timeout
*/
public function slow(array $data = [], int $timeout = self::SLOW_LOG_TIMEOUT_DEFAULT)
{
$this->log[] = [
$this->message(),
$data,
];
if ($this->delay() > $timeout) {
foreach ($this->log as $item) {
info($item[0],$item[1]);
}
$this->log = [];
}
}
/**
* 消息体
*
* @return string
*/
protected function message(): string
{
$delay = $this->delay();
return "$this->mark\t$delay";
}
}
另外,日志我们也做了跟踪策略,如果想探讨一下,我之后再贴出来。
public function recordRequest(RequestHandled $event)
{
if (! Telescope::isRecording() ||
$this->shouldIgnoreHttpMethod($event) ||
$this->shouldIgnoreStatusCode($event)) {
return;
}
$startTime = defined('LARAVEL_START') ? LARAVEL_START : $event->request->server('REQUEST_TIME_FLOAT');
Telescope::recordRequest(IncomingEntry::make([
'ip_address' => $event->request->ip(),
'uri' => str_replace($event->request->root(), '', $event->request->fullUrl()) ?: '/',
'method' => $event->request->method(),
'controller_action' => optional($event->request->route())->getActionName(),
'middleware' => array_values(optional($event->request->route())->gatherMiddleware() ?? []),
'headers' => $this->headers($event->request->headers->all()),
'payload' => $this->payload($this->input($event->request)),
'session' => $this->payload($this->sessionVariables($event->request)),
'response_status' => $event->response->getStatusCode(),
'response' => $this->response($event->response),
'duration' => $startTime ? floor((microtime(true) - $startTime) * 1000) : null,
'memory' => round(memory_get_peak_usage(true) / 1024 / 1024, 1),
]));
}
这种东西参考现成的写法就可以了
推荐文章: