本文介绍了 “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官方的介绍,其他的内容就是一些很基础的了!