中间件之系统日志 - Thinkphp6

本文介绍了 “Thinkphp6” 的系统日志编写内容。

全局的系统日志定义以及局部模块的日志定义。

用到内容 “中间件”。

全局:

在app\middleware.php文件内添加自定义中间件。

\app\common\vendor\LogServer::class,

局部:

在模块下面新建middleware.php文件并添加中间件。(如上)。

以下是日志类文件。

<?php


namespace app\general\vendor;

use app\common\model\SystemLogs;
use think\facade\Cache;
use think\facade\Session;

class LogServer
{
    protected $_request;
    protected $_insertData = [];
    public function handle($request, \Closure $next)
    {
        // 添加中间件执行代码
        $this->_request = $request;
        $this->_insertData['header'] = json_encode($request->header());
        $this->_insertData['ip_address'] = $request->server('REMOTE_ADDR');
        $this->_insertData['url'] = $request->param('s');
        if($request->method() == "POST"){
            $this->_insertData['param'] = json_encode($request->post());
        }else{
            $this->_insertData['param'] = json_encode($request->get());
        }
        $this->_insertData['method'] = $request->method();
        $this->_insertData['addtime'] = time();
        return $next($request);
    }

    public function end(\think\Response $response)
    {
        // 回调行为
        $this->_insertData['class_name'] = app('request')->controller();
        $this->_insertData['class_method'] = app('request')->action();
        if($this->_insertData['method'] != "GET"){
            $this->_insertData['response'] = $response->getContent();
        }
        $ModelSystemLogs = new SystemLogs();
        $ModelSystemLogs->insertLog($this->_insertData);
    }
}

方法end是后置执行方法。

在用户访问这个方法以后去执行的。

方法handle是前置执行方法。

在用户访问之前执行。(详细解释自行百度哈!)

我们在end方法里面判断如果是异步请求的API接口的话,就去获取返回的内容。

并且插入数据库SystemLog表内。

结束~

主要是要了解,中间件的前置跟后置的定义。

怕有人偷懒,我也贴上前置跟后置的介绍吧。TP官方的介绍,其他的内容就是一些很基础的了!

中间件 · ThinkPHP6.0完全开发手册 · 看云 ThinkPHP`6.0`基于精简核心和统一用法两大原则在`5.1`的基础上对底层架构做了进一步的优化改进,并更加规范化。icon-default.png?t=M3K6https://www.kancloud.cn/manual/thinkphp6_0/1037493

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值