【laravel】增加记录日志的中间件-用户发送请求和响应的日志记录

在这里插入图片描述

在/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);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值