💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
关键是两个,1是修改配置文件,指定自定义的驱动。2是自定义驱动的save方法 直接上代码 config/log.php ``` <?php // +---------------------------------------------------------------------- // | 日志设置 // +---------------------------------------------------------------------- return [ // 默认日志记录通道 'default' => env('log.channel', 'file'), // 日志记录级别 'level' => [], // 日志类型记录的通道 ['error'=>'email',...] 'type_channel' => [], // 关闭全局日志写入 'close' => false, // 全局日志处理 支持闭包 'processor' => null, //ThinkPHP对系统的日志按照级别来分类记录,按照PSR-3日志规范,日志的级别从低到高依次为: debug, info, notice, warning, error, critical, alert, emergency,ThinkPHP额外增加了一个sql日志级别仅用于记录SQL日志(并且仅当开启数据库调试模式有效)。 // 日志通道列表 'channels' => [ 'file' => [ // 日志记录方式 //'type' => 'File', 'type' => '\app\driver\log\Tp6Log', // 日志保存目录 'path' => '', // 单文件日志写入 'single' => false, // 独立日志级别 'apart_level' => ['error', 'sql','user','fun','pay','refund','order','cancelBadOrder','ar','job'], // 最大日志文件数量 'max_files' => 0, // 使用JSON格式记录 'json' => false, // 文件大小 'file_size' => 1024*1024*2, // 日志处理 'processor' => null, // 关闭通道日志写入 'close' => false, // 日志输出格式化 'format' => '[%s][%s] %s', // 是否实时写入 'realtime_write' => true, ], // 其它日志通道配置 ], ]; ``` app\drive\log\Tp6Log.php ``` <?php declare (strict_types=1); namespace app\driver\log; use DateTime; use DateTimeZone; use Exception; use think\App; use think\contract\LogHandlerInterface; use think\facade\Request; /** * 本地化调试输出到文件 */ class Tp6Log implements LogHandlerInterface { /** * 配置参数 * @var array */ protected $config = [ 'time_format' => 'c', 'single' => false, 'file_size' => 2097152, 'path' => '', 'apart_level' => [], 'max_files' => 0, 'json' => false, 'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, 'format' => '[%s][%s] %s', ]; protected $app; // 实例化并传入参数 public function __construct(App $app, $config = []) { $this->app = $app; if (is_array($config)) { $this->config = array_merge($this->config, $config); } if (empty($this->config['format'])) { $this->config['format'] = '[%s][%s] %s'; } if (empty($this->config['path'])) { $this->config['path'] = $app->getRuntimePath() . 'log'; } if (substr($this->config['path'], -1) != DIRECTORY_SEPARATOR) { $this->config['path'] .= DIRECTORY_SEPARATOR; } } /** * 日志写入接口 * @access public * @param array $log 日志信息 * @return bool */ public function save(array $log): bool { $destination = $this->getMasterLogFile(); $path = dirname($destination); !is_dir($path) && mkdir($path, 0755, true); $info = []; // 日志信息封装 $time = DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']); $request = Request::instance(); //新增 $requestInfo = [ 'ip' => $request->ip(), 'method' => $request->method(), 'host' => $request->host(), 'uri' => $request->url() ]; if(isset($log['sql'][0]) && strpos('CONNECT',$log['sql'][0])){ } if (!$this->config['json']) { $debugInfo = [ 'param' => '[ PARAM ] ' . var_export($request->param(), true), 'header' => '[ HEADER ] ' . var_export($request->header(), true) ]; foreach ($debugInfo as $row) { array_unshift($info, $row); } // 增加额外的调试信息 $runtime = round(microtime(true) - $this->app->getBeginTime(), 10); $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; $memory_use = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2); $time_str = '[运行时间:' . number_format($runtime, 6) . 's] [吞吐率:' . $reqs . 'req/s]'; $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; $file_load = ' [文件加载:' . count(get_included_files()) . ']'; array_unshift($info, $time_str . $memory_str . $file_load); array_unshift($info, "---------------------------------------------------------------\r\n[{$time}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}"); } foreach ($log as $type => $val) { $message = []; foreach ($val as $msg) { if (!is_string($msg)) { $msg = var_export($msg, true); } $message[] = $this->config['json'] ? json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) : sprintf($this->config['format'], $time, $type, $msg); } if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) { //这一句很关键,可以给mysql或者其他独立的日志,也加上请求和时间等信息 array_unshift($message, "---------------------------------------------------------------\r\n[{$time}] {$requestInfo['ip']} {$requestInfo['method']} {$requestInfo['host']}{$requestInfo['uri']}"); // 独立记录的日志级别 $filename = $this->getApartLevelFile($path, $type); $this->write($message, $filename); continue; } $info[$type] = $message; } if ($info) { return $this->write($info, $destination); } return true; } /** * 获取主日志文件名 * @access public * @return string */ protected function getMasterLogFile(): string { if ($this->config['max_files']) { $files = glob($this->config['path'] . '*.log'); try { if (count($files) > $this->config['max_files']) { unlink($files[0]); } } catch (Exception $e) { // } } if ($this->config['single']) { $name = is_string($this->config['single']) ? $this->config['single'] : 'single'; $destination = $this->config['path'] . $name . '.log'; } else { if ($this->config['max_files']) { $filename = date('Ymd') . '.log'; } else { $filename = date('Ym') . DIRECTORY_SEPARATOR . date('d') . '.log'; } $destination = $this->config['path'] . $filename; } return $destination; } /** * 获取独立日志文件名 * @access public * @param string $path 日志目录 * @param string $type 日志类型 * @return string */ protected function getApartLevelFile(string $path, string $type): string { if ($this->config['single']) { $name = is_string($this->config['single']) ? $this->config['single'] : 'single'; $name .= '_' . $type; } elseif ($this->config['max_files']) { $name = date('Ymd') . '_' . $type; } else { $name = date('d') . '_' . $type; } return $path . DIRECTORY_SEPARATOR . $name . '.log'; } /** * 日志写入 * @access protected * @param array $message 日志信息 * @param string $destination 日志文件 * @return bool */ protected function write(array $message, string $destination): bool { // 检测日志文件大小,超过配置大小则备份日志文件重新生成 $this->checkLogSize($destination); $info = []; foreach ($message as $type => $msg) { $info[$type] = is_array($msg) ? implode(PHP_EOL, $msg) : $msg; } $message = implode(PHP_EOL, $info) . PHP_EOL; return error_log($message, 3, $destination); } /** * 检查日志文件大小并自动生成备份文件 * @access protected * @param string $destination 日志文件 * @return void */ protected function checkLogSize(string $destination): void { if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) { try { rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination)); } catch (Exception $e) { // } } } } ``` 效果如下 mysql ``` --------------------------------------------------------------- [2021-11-11T09:05:00+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [2021-11-11T09:05:00+08:00][sql] CONNECT:[ UseTime:0.083536s ] mysql:host=47.99.78.253;port=3306;dbname=ad_qingclouds_c;charset=utf8 --------------------------------------------------------------- [2021-11-11T09:05:01+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [2021-11-11T09:05:01+08:00][sql] SHOW FULL COLUMNS FROM `user` [ RunTime:0.056446s ] --------------------------------------------------------------- [2021-11-11T09:05:01+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [2021-11-11T09:05:01+08:00][sql] SELECT * FROM `user` WHERE `access_token` = '5bdb8c308b77089bb68754ea37717dd2' LIMIT 1 [ RunTime:0.055739s ] --------------------------------------------------------------- [2021-11-11T09:05:01+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [2021-11-11T09:05:01+08:00][sql] SHOW FULL COLUMNS FROM `system_config` [ RunTime:0.060319s ] ``` --------------------------------------------------------------- ``` [2021-11-11T09:05:01+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [运行时间:0.305206s] [吞吐率:3.28req/s] [内存消耗:3,629.77kb] [文件加载:145] [ HEADER ] array ( 'connection' => 'close', 'user-agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 'content-type' => 'application/x-www-form-urlencoded', 'accept' => '*/*', 'origin' => 'http://localhost:4100', 'sec-fetch-site' => 'same-origin', 'sec-fetch-mode' => 'cors', 'sec-fetch-dest' => 'empty', 'referer' => 'http://localhost:4100/', 'accept-language' => 'zh-CN,zh-TW;q=0.9,zh;q=0.8,en-US;q=0.7,en;q=0.6', 'cookie' => 'Phpstorm-262f24aa=fae27331-cd1a-4ce2-982f-52f41bd8c1f0; Webstorm-1bff894e=03b215c5-737b-4ab8-83b2-d225427ad987; EGG_SESS=tDY1kbt9o6NheiNmX1fErLhQvJBtAIKxPlxB98-6sQwe0-RkHzejSB8i3uXkzdbfH79HB6RNchgIKNBTBkfJWkwfCT4Ozy0N97Rk028vPE0MZE8p0sN9v16L7eQZ4sF4newIVv2REd9RXzCH8U9CKD1DgTAM23BfTfTaN3X3dTcZg0vZNVPWB-5P_Wh_C1LsAGHDyjkAVVE-uUcg0EZT2rNsCC_uJJW3fLLldEfx59MK7vO9gG1IwW8rgiFF1OP_Gm-0XrclP2_sx4A6lw4ZI4TAj_T-xjukYMzuri1Rp2mXtf5uyLkxIdb6oxi865426J_EUbGBKmgU5Hfxv3V8i8MfvOf6NvBp-aiYRASpQVhOZ348P4vv3TiODVdramlRvsjt86adzZUVi5E4ZD_uz6RkOm6fhSzQNySOqq4y_VXgAGhott7Jlhba2ewQB6qGA1_t1LLLtJUMVL9yXLypo8lOccbbSfjDZvOe9LWQz28W1B85AbvESp0Pqadk1LYDl6GTxuT4r-ed6j4IjzWfQzEPjqqxMP7gSF6djqlvK1VjhSz6LwVE0hxOxVQ_QmzMgGbTHMT1lPnnAMOkBg7jKqNrW1mYv5htfNTLkvoDTp-VI55cgN66vlx7Wu6tP4KUrSrg5AkNDfEYEFIyb89ZL4Dc5U6wpJxfLufC8ZPOkRliieUOsLYrdxp66Jw1jxp0x5NfNVHMDq0qpRsqrXdwOjUWmvGhY1nC7EIbC91Fz295qvlBpv_SowOLKa_p10WwK1ppaBNWh2RsQyAUYN3wN8hIFGHsgavjndhddbCB4IssEfhgN-15XnKM2M2Eg28KmCtyR-Zg1m76lJRLcexhi32UyHBHuo9RvM08DqmF68MlIl4LLZb9Nhwm_n9ayy3caMvBWkW7oRll33n8FOz48T7GQXqKr3GANQxXaq8VJ9k=; UM_distinctid=17cee0244cd10e-0cefb9b964c974-c343365-1fa400-17cee0244cef85; CNZZDATA1258685886=2051018770-1636073879-%7C1636073879', 'postman-token' => 'ca1d434f-51c6-49b5-a4eb-7f82531d9ae3', 'host' => 'api.qingyun.com', 'accept-encoding' => 'gzip, deflate, br', 'content-length' => '163', 'x-forwarded-for' => '127.0.0.1', 'x-forwarded-port' => '4100', 'x-forwarded-proto' => 'http', 'x-forwarded-host' => 'localhost:4100', ) [ PARAM ] array ( 'is_dev' => '1', 'build' => '310', 'access_token' => '5bdb8c308b77089bb68754ea37717dd2', 'env' => 'wap', 'act' => '/Dictionary/getDictData', 'timestamp' => '1636524784', 'sign' => '6b898e0b0f453b94e820ba5acadf7b40', ) --------------------------------------------------------------- [2021-11-11T09:05:01+08:00] 127.0.0.1 POST localhost:4100/api/Dictionary/getDictData [运行时间:0.309771s] [吞吐率:3.23req/s] [内存消耗:3,725.85kb] [文件加载:151] [ HEADER ] array ( 'connection' => 'close', 'user-agent' => 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1', 'content-type' => 'application/x-www-form-urlencoded', 'accept' => '*/*', 'origin' => 'http://localhost:4100', 'sec-fetch-site' => 'same-origin', 'sec-fetch-mode' => 'cors', 'sec-fetch-dest' => 'empty', 'referer' => 'http://localhost:4100/', 'accept-language' => 'zh-CN,zh-TW;q=0.9,zh;q=0.8,en-US;q=0.7,en;q=0.6', 'cookie' => 'Phpstorm-262f24aa=fae27331-cd1a-4ce2-982f-52f41bd8c1f0; Webstorm-1bff894e=03b215c5-737b-4ab8-83b2-d225427ad987; EGG_SESS=tDY1kbt9o6NheiNmX1fErLhQvJBtAIKxPlxB98-6sQwe0-RkHzejSB8i3uXkzdbfH79HB6RNchgIKNBTBkfJWkwfCT4Ozy0N97Rk028vPE0MZE8p0sN9v16L7eQZ4sF4newIVv2REd9RXzCH8U9CKD1DgTAM23BfTfTaN3X3dTcZg0vZNVPWB-5P_Wh_C1LsAGHDyjkAVVE-uUcg0EZT2rNsCC_uJJW3fLLldEfx59MK7vO9gG1IwW8rgiFF1OP_Gm-0XrclP2_sx4A6lw4ZI4TAj_T-xjukYMzuri1Rp2mXtf5uyLkxIdb6oxi865426J_EUbGBKmgU5Hfxv3V8i8MfvOf6NvBp-aiYRASpQVhOZ348P4vv3TiODVdramlRvsjt86adzZUVi5E4ZD_uz6RkOm6fhSzQNySOqq4y_VXgAGhott7Jlhba2ewQB6qGA1_t1LLLtJUMVL9yXLypo8lOccbbSfjDZvOe9LWQz28W1B85AbvESp0Pqadk1LYDl6GTxuT4r-ed6j4IjzWfQzEPjqqxMP7gSF6djqlvK1VjhSz6LwVE0hxOxVQ_QmzMgGbTHMT1lPnnAMOkBg7jKqNrW1mYv5htfNTLkvoDTp-VI55cgN66vlx7Wu6tP4KUrSrg5AkNDfEYEFIyb89ZL4Dc5U6wpJxfLufC8ZPOkRliieUOsLYrdxp66Jw1jxp0x5NfNVHMDq0qpRsqrXdwOjUWmvGhY1nC7EIbC91Fz295qvlBpv_SowOLKa_p10WwK1ppaBNWh2RsQyAUYN3wN8hIFGHsgavjndhddbCB4IssEfhgN-15XnKM2M2Eg28KmCtyR-Zg1m76lJRLcexhi32UyHBHuo9RvM08DqmF68MlIl4LLZb9Nhwm_n9ayy3caMvBWkW7oRll33n8FOz48T7GQXqKr3GANQxXaq8VJ9k=; UM_distinctid=17cee0244cd10e-0cefb9b964c974-c343365-1fa400-17cee0244cef85; CNZZDATA1258685886=2051018770-1636073879-%7C1636073879', 'postman-token' => 'ca1d434f-51c6-49b5-a4eb-7f82531d9ae3', 'host' => 'api.qingyun.com', 'accept-encoding' => 'gzip, deflate, br', 'content-length' => '163', 'x-forwarded-for' => '127.0.0.1', 'x-forwarded-port' => '4100', 'x-forwarded-proto' => 'http', 'x-forwarded-host' => 'localhost:4100', ) [ PARAM ] array ( 'is_dev' => '1', 'build' => '310', 'access_token' => '5bdb8c308b77089bb68754ea37717dd2', 'env' => 'wap', 'act' => '/Dictionary/getDictData', 'timestamp' => '1636524784', 'sign' => '6b898e0b0f453b94e820ba5acadf7b40', ) ```