在/app/http/Middleware/中添加日志中间件UserRequestAndResponseLog.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Storage;
class UserRequestAndResponseLog
{
protected $code;
protected $sequence;
public function __construct()
{
$this->code = get_route_code();
$this->sequence = str_pad(microtime(true), 15, 0);
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (auth('api')->check()) {
$id = auth('api')->id();
$mobile = auth('api')->user()->broker_mobile;
$this->request($id, $mobile, $request);
}
$response = $next($request);
if ($response instanceof JsonResponse && isset($id, $mobile)) {
$this->response($id, $mobile, $response);
}
$this->time();
$this->sql();
return $response;
}
protected function time():void
{
$start = str_pad(LARAVEL_START, 15, 0);
$end = str_pad(microtime(true), 15, 0);
/** @var \Illuminate\Filesystem\Filesystem $disk */
$disk = Storage::disk('storage');
$standard = config('develop.runtime-lower-limit');
$time = ($end - LARAVEL_START) * 1000;
switch (true) {
case $time > $standard:
$mark = '超过[>]';
$diff = $time - $standard;
break;
case $time === $standard:
$mark = '持平[=]';
$diff = 0;
break;
default:
$mark = '低于[<]';
$diff = $time - $standard;
}
$message = "请求序号[{$this->sequence}] 请求接口[{$this->code}] 开始时间[{$start}] 结束时间[{$end}] 运行时间[{$time}] {$mark}[{$standard}] {$diff}毫秒";
$path = '/logs/' . date('Ym') . '/' . date('d') . '/' . 'time.log';
$this->write($disk, $path, $message);
if ($diff > 0) {
$path = str_replace_first('time.log', 'slow-time.log', $path);
$this->write($disk, $path, $message);
}
}
protected function sql():void
{
$sql = allSql();
if (count($sql) > 10) {
$message = "请求序号[{$this->sequence}] 请求接口[{$this->code}] 查询数据库次数超过 10[" . count($sql) . "] 次\r\n";
$data = [];
foreach (\DB::getQueryLog() as $log) {
if (!array_key_exists($log['query'], $data)) {
$data[$log['query']] = 0;
}
++ $data[$log['query']];
}
arsort($data);
$path = '/logs/' . date('Ym') . '/' . date('d') . '/' . 'sql.log';
/** @var \Illuminate\Filesystem\Filesystem $disk */
$this->write(Storage::disk('storage'), $path, $message . var_export($data, true));
}
}
protected function write($disk, $path, $message):void
{
if ($disk->exists($path) === false) {
$disk->put($path, $message);
} else {
$disk->append($path, $message);
}
}
protected function request($id, $mobile, $request):void
{
$input = $request->input();
if (array_key_exists('data', $input)) {
$input['data'] = json_decode($input['data'], true);
}
logger(sprintf('%s-%s-%s-request', $id, $mobile, $this->sequence), $input);
}
protected function response($id, $mobile, JsonResponse $response):void
{
$output = json_decode($response->getContent(), true);
if (json_last_error() === JSON_ERROR_NONE) {
logger(sprintf('%s-%s-%s-response', $id, $mobile, $this->sequence), $output);
}
}
}