This commit is contained in:
Your Name
2026-03-01 14:17:59 +08:00
parent 65aa12f146
commit a07e844c47
6071 changed files with 777651 additions and 0 deletions
@@ -0,0 +1,163 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
declare(strict_types = 1);
namespace think\log;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Stringable;
use think\contract\LogHandlerInterface;
use think\Event;
use think\event\LogRecord;
use think\event\LogWrite;
class Channel implements LoggerInterface
{
use LoggerTrait;
/**
* 日志信息
* @var array
*/
protected $log = [];
/**
* 关闭日志
* @var bool
*/
protected $close = false;
public function __construct(protected string $name, protected LogHandlerInterface $logger, protected array $allow, protected bool $lazy, protected Event $event)
{
}
/**
* 关闭通道
*/
public function close(): void
{
$this->clear();
$this->close = true;
}
/**
* 清空日志
*/
public function clear(): void
{
$this->log = [];
}
/**
* 记录日志信息
* @access public
* @param mixed $msg 日志信息
* @param string $type 日志级别
* @param array $context 替换内容
* @param bool $lazy
* @return $this
*/
public function record($msg, string $type = 'info', array $context = [], bool $lazy = true)
{
if ($this->close || (!empty($this->allow) && !in_array($type, $this->allow))) {
return $this;
}
if ($msg instanceof Stringable) {
$msg = $msg->__toString();
}
if (is_string($msg) && !empty($context)) {
$replace = [];
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
$msg = strtr($msg, $replace);
}
if (!empty($msg) || 0 === $msg) {
$this->log[$type][] = $msg;
if ($this->event) {
$this->event->trigger(new LogRecord($type, $msg));
}
}
if (!$this->lazy || !$lazy) {
$this->save();
}
return $this;
}
/**
* 实时写入日志信息
* @access public
* @param mixed $msg 调试信息
* @param string $type 日志级别
* @param array $context 替换内容
* @return $this
*/
public function write($msg, string $type = 'info', array $context = [])
{
return $this->record($msg, $type, $context, false);
}
/**
* 获取日志信息
* @return array
*/
public function getLog(): array
{
return $this->log;
}
/**
* 保存日志
* @return bool
*/
public function save(): bool
{
$log = $this->log;
if ($this->event) {
$event = new LogWrite($this->name, $log);
$this->event->trigger($event);
$log = $event->log;
}
if ($this->logger->save($log)) {
$this->clear();
return true;
}
return false;
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string|Stringable $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = []): void
{
$this->record($message, $level, $context);
}
public function __call($method, $parameters)
{
$this->log($method, ...$parameters);
}
}
@@ -0,0 +1,34 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace think\log;
use think\Log;
/**
* Class ChannelSet
* @package think\log
* @mixin Channel
*/
class ChannelSet
{
public function __construct(protected Log $log, protected array $channels)
{
}
public function __call($method, $arguments)
{
foreach ($this->channels as $channel) {
$this->log->channel($channel)->{$method}(...$arguments);
}
}
}
@@ -0,0 +1,207 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace think\log\driver;
use think\App;
use think\contract\LogHandlerInterface;
/**
* 本地化调试输出到文件
*/
class File 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',
];
// 实例化并传入参数
public function __construct(App $app, $config = [])
{
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']);
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'])) {
// 独立记录的日志级别
$filename = $this->getApartLevelFile($path, $type);
$this->write($message, $filename);
continue;
}
$info[$type] = $message;
}
if ($info) {
return $this->write($info, $destination);
}
return true;
}
/**
* 日志写入
* @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 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']) {
set_error_handler(function ($errno, $errstr, $errfile, $errline) {});
unlink($files[0]);
restore_error_handler();
}
} 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 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) {
//
}
}
}
}
@@ -0,0 +1,307 @@
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2021 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: luofei614 <weibo.com/luofei614>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace think\log\driver;
use Psr\Container\NotFoundExceptionInterface;
use think\App;
use think\contract\LogHandlerInterface;
/**
* github: https://github.com/luofei614/SocketLog
* @author luofei614<weibo.com/luofei614>
*/
class Socket implements LogHandlerInterface
{
protected $config = [
// socket服务器地址
'host' => 'localhost',
// socket服务器端口
'port' => 1116,
// 是否显示加载的文件列表
'show_included_files' => false,
// 日志强制记录到配置的client_id
'force_client_ids' => [],
// 限制允许读取日志的client_id
'allow_client_ids' => [],
// 调试开关
'debug' => false,
// 输出到浏览器时默认展开的日志级别
'expand_level' => ['debug'],
// 日志头渲染回调
'format_head' => null,
// curl opt
'curl_opt' => [
CURLOPT_CONNECTTIMEOUT => 1,
CURLOPT_TIMEOUT => 10,
],
];
protected $css = [
'sql' => 'color:#009bb4;',
'sql_warn' => 'color:#009bb4;font-size:14px;',
'error' => 'color:#f4006b;font-size:14px;',
'page' => 'color:#40e2ff;background:#171717;',
'big' => 'font-size:20px;color:red;',
];
protected $allowForceClientIds = []; //配置强制推送且被授权的client_id
protected $clientArg = [];
/**
* 架构函数
* @access public
* @param App $app
* @param array $config 缓存参数
*/
public function __construct(protected App $app, array $config = [])
{
if (!empty($config)) {
$this->config = array_merge($this->config, $config);
}
if (!isset($config['debug'])) {
$this->config['debug'] = $app->isDebug();
}
}
/**
* 调试输出接口
* @access public
* @param array $log 日志信息
* @return bool
*/
public function save(array $log = []): bool
{
if (!$this->check()) {
return false;
}
$trace = [];
if ($this->config['debug']) {
if ($this->app->exists('request')) {
$currentUri = $this->app->request->url(true);
} else {
$currentUri = 'cmd:' . implode(' ', $_SERVER['argv'] ?? []);
}
if (!empty($this->config['format_head'])) {
try {
$currentUri = $this->app->invoke($this->config['format_head'], [$currentUri]);
} catch (NotFoundExceptionInterface $notFoundException) {
// Ignore exception
}
}
// 基本信息
$trace[] = [
'type' => 'group',
'msg' => $currentUri,
'css' => $this->css['page'],
];
}
$expandLevel = array_flip($this->config['expand_level']);
foreach ($log as $type => $val) {
$trace[] = [
'type' => isset($expandLevel[$type]) ? 'group' : 'groupCollapsed',
'msg' => '[ ' . $type . ' ]',
'css' => $this->css[$type] ?? '',
];
foreach ($val as $msg) {
if (!is_string($msg)) {
$msg = var_export($msg, true);
}
$trace[] = [
'type' => 'log',
'msg' => $msg,
'css' => '',
];
}
$trace[] = [
'type' => 'groupEnd',
'msg' => '',
'css' => '',
];
}
if ($this->config['show_included_files']) {
$trace[] = [
'type' => 'groupCollapsed',
'msg' => '[ file ]',
'css' => '',
];
$trace[] = [
'type' => 'log',
'msg' => implode("\n", get_included_files()),
'css' => '',
];
$trace[] = [
'type' => 'groupEnd',
'msg' => '',
'css' => '',
];
}
$trace[] = [
'type' => 'groupEnd',
'msg' => '',
'css' => '',
];
$tabid = $this->getClientArg('tabid');
if (!$clientId = $this->getClientArg('client_id')) {
$clientId = '';
}
if (!empty($this->allowForceClientIds)) {
//强制推送到多个client_id
foreach ($this->allowForceClientIds as $forceClientId) {
$clientId = $forceClientId;
$this->sendToClient($tabid, $clientId, $trace, $forceClientId);
}
} else {
$this->sendToClient($tabid, $clientId, $trace, '');
}
return true;
}
/**
* 发送给指定客户端
* @access protected
* @author Zjmainstay
* @param $tabid
* @param $clientId
* @param $logs
* @param $forceClientId
*/
protected function sendToClient($tabid, $clientId, $logs, $forceClientId)
{
$logs = [
'tabid' => $tabid,
'client_id' => $clientId,
'logs' => $logs,
'force_client_id' => $forceClientId,
];
$msg = json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PARTIAL_OUTPUT_ON_ERROR);
$address = '/' . $clientId; //将client_id作为地址, server端通过地址判断将日志发布给谁
$this->send($this->config['host'], $this->config['port'], $msg, $address);
}
/**
* 检测客户授权
* @access protected
* @return bool
*/
protected function check()
{
$tabid = $this->getClientArg('tabid');
//是否记录日志的检查
if (!$tabid && !$this->config['force_client_ids']) {
return false;
}
//用户认证
$allowClientIds = $this->config['allow_client_ids'];
if (!empty($allowClientIds)) {
//通过数组交集得出授权强制推送的client_id
$this->allowForceClientIds = array_intersect($allowClientIds, $this->config['force_client_ids']);
if (!$tabid && count($this->allowForceClientIds)) {
return true;
}
$clientId = $this->getClientArg('client_id');
if (!in_array($clientId, $allowClientIds)) {
return false;
}
} else {
$this->allowForceClientIds = $this->config['force_client_ids'];
}
return true;
}
/**
* 获取客户参数
* @access protected
* @param string $name
* @return string
*/
protected function getClientArg(string $name)
{
if (!$this->app->exists('request')) {
return '';
}
if (empty($this->clientArg)) {
if (empty($socketLog = $this->app->request->header('socketlog'))) {
if (empty($socketLog = $this->app->request->header('User-Agent'))) {
return '';
}
}
if (!preg_match('/SocketLog\((.*?)\)/', $socketLog, $match)) {
$this->clientArg = ['tabid' => null, 'client_id' => null];
return '';
}
parse_str($match[1] ?? '', $this->clientArg);
}
if (isset($this->clientArg[$name])) {
return $this->clientArg[$name];
}
return '';
}
/**
* @access protected
* @param string $host - $host of socket server
* @param int $port - $port of socket server
* @param string $message - 发送的消息
* @param string $address - 地址
* @return bool
*/
protected function send($host, $port, $message = '', $address = '/')
{
$url = 'http://' . $host . ':' . $port . $address;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->config['curl_opt'][CURLOPT_CONNECTTIMEOUT] ?? 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->config['curl_opt'][CURLOPT_TIMEOUT] ?? 10);
$headers = [
"Content-Type: application/json;charset=UTF-8",
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); //设置header
return curl_exec($ch);
}
}