thinkphp6: 用middleware 记录操作日志(php 8.1.1 / thinkphp v6.0.10LTS )


一,编写php代码:

1,创建写日志的middleware:
liuhongdi@lhdpc:/data/php/admapi$ php think make:middleware AdminLog
Middleware:app\middleware\AdminLog created successfully. 
2,middleware/AdminLog.php
<?php
declare (strict_types = 1);
 
namespace app\middleware;
 
use app\lib\util\BusinessLog;
 
class AdminLog
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
          //得到要log的数据
          $userId = 123;
          $host = $request->server("HTTP_HOST");
          $uri = $request->server("REQUEST_URI");
          $ua = $request->server("HTTP_USER_AGENT");
          $method = $request->server("REQUEST_METHOD");
          $param = $request->request();
          //放入数组
          $content = [
              "userId"=>$userId,
              "host"=>$host,
              "uri"=>$uri,
              "ua"=>$ua,
              "method"=>$method,
              "param"=>$param,
          ];
         //log
        $log = new BusinessLog("admin");
        $log->log($content);
 
        //返回
        return $next($request);
    }
}

说明:用户id应该从token或session获取,此处仅演示用

3,app/middleware.php
<?php
// 全局中间件定义文件
return [
    app\middleware\AdminLog::class,
]; 
4,lib/util/BusinessLog.php
<?php
namespace app\lib\util;
 
class BusinessLog{
 
    var $baseDir;
    var $subDir;
    var $fileName;
    //构造
    function __construct($type){
        if ($type == "admin") {
            $this->baseDir = "/data/businesslog/adminlog";
            $this->subDir = date("Ym");
            $this->fileName = date("Ymd") . ".txt";
        }
    }
    //记录
    function log($content){
        if (is_array($content)) {
            $contentStr = var_export($content, true);
        } else {
            $contentStr = $content;
        }
        $fileDir = $this->baseDir."/".$this->subDir;
        if (!is_dir($fileDir)) {
            mkdir($fileDir, 0777, true);
        }
 
        $filePath = $fileDir . "/" . $this->fileName;
        $ip = request()->ip();
        $logContent = date("Y-m-d H:i:s") . "--" . $ip . "--" . $contentStr . "\r\n";
        error_log($logContent, 3, $filePath);
    }
}

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,测试效果

1,访问:
http://192.168.219.6:8000/article/onemedia?id=1
返回: 2,查看日志:
liuhongdi@lhdpc:~$ tail -100 /data/businesslog/adminlog/202201/20220113.txt
2022-01-13 12:30:25--192.168.219.1--array (
  'userId' => 123,
  'host' => '192.168.219.6:8000',
  'uri' => '/article/onemedia?id=1',
  'ua' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
  'method' => 'GET',
  'param' =>
  array (
    's' => 'article/onemedia',
    'id' => '1',
  ),
)

三,查看php和thinkphp的版本: 

php:
liuhongdi@lhdpc:/data/php/admapi$ php --version
PHP 8.1.1 (cli) (built: Dec 20 2021 16:12:16) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies 
thinkphp:
liuhongdi@lhdpc:/var/www/html$ cd /data/php/admapi/
liuhongdi@lhdpc:/data/php/admapi$ php think version
v6.0.10LTS