replace console with logger

This commit is contained in:
sunxyw 2022-06-08 23:11:17 +08:00
parent 1c40896dc0
commit 4fe74eb5fe
No known key found for this signature in database
GPG Key ID: CEA01A083E98C578
51 changed files with 210 additions and 245 deletions

View File

@ -18,7 +18,6 @@ use ZM\API\OneBotV11;
use ZM\API\TuringAPI;
use ZM\Config\ZMConfig;
use ZM\ConnectionManager\ConnectionObject;
use ZM\Console\Console;
use ZM\Context\Context;
use ZM\Event\EventDispatcher;
use ZM\Exception\InterruptException;
@ -127,7 +126,7 @@ class Hello
if (MessageUtil::isAtMe(ctx()->getMessage(), ctx()->getRobotId())) {
$msg = str_replace(CQ::at(ctx()->getRobotId()), '', ctx()->getMessage());
ctx()->setMessage('机器人' . $msg);
Console::info(ctx()->getMessage());
logger()->info(ctx()->getMessage());
}
return true;
}
@ -192,7 +191,7 @@ class Hello
*/
public function onConnect(ConnectionObject $conn)
{
Console::info('机器人 ' . $conn->getOption('connect_id') . ' 已连接!');
logger()->info('机器人 ' . $conn->getOption('connect_id') . ' 已连接!');
}
/**
@ -201,7 +200,7 @@ class Hello
*/
public function onDisconnect(ConnectionObject $conn)
{
Console::info('机器人 ' . $conn->getOption('connect_id') . ' 已断开连接!');
logger()->info('机器人 ' . $conn->getOption('connect_id') . ' 已断开连接!');
}
/**
@ -221,7 +220,7 @@ class Hello
*/
public function closeUnknownConn()
{
Console::info('Unknown connection , I will close it.');
logger()->info('发现了未知的 Websocket 连接,正在断开');
server()->disconnect(ctx()->getConnection()->getFd());
}

View File

@ -9,7 +9,6 @@ use ZM\Annotation\Http\HandleAfter;
use ZM\Annotation\Http\HandleBefore;
use ZM\Annotation\Http\HandleException;
use ZM\Annotation\Http\MiddlewareClass;
use ZM\Console\Console;
use ZM\Http\MiddlewareInterface;
/**
@ -35,7 +34,7 @@ class TimerMiddleware implements MiddlewareInterface
*/
public function onAfter()
{
Console::info('Using ' . round((microtime(true) - $this->starttime) * 1000, 3) . ' ms.');
logger()->info('Using ' . round((microtime(true) - $this->starttime) * 1000, 3) . ' ms.');
}
/**
@ -44,7 +43,7 @@ class TimerMiddleware implements MiddlewareInterface
*/
public function onException(Exception $e)
{
Console::error('Using ' . round((microtime(true) - $this->starttime) * 1000, 3) . ' ms but an Exception occurred.');
logger()->error('Using ' . round((microtime(true) - $this->starttime) * 1000, 3) . ' ms but an Exception occurred.');
throw $e;
}
}

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace ZM\API;
use Stringable;
use ZM\Console\Console;
use ZM\Entity\CQObject;
class CQ
@ -207,7 +206,7 @@ class CQ
return self::buildCQ('music', ['type' => $type, 'id' => $id_or_url]);
case 'custom':
if ($title === null || $audio === null) {
Console::warning(zm_internal_errcode('E00035') . '传入CQ码实例的标题和音频链接不能为空');
logger()->warning(zm_internal_errcode('E00035') . '传入CQ码实例的标题和音频链接不能为空');
return ' ';
}
$optional_values = [
@ -216,7 +215,7 @@ class CQ
];
return self::buildCQ('music', ['type' => 'custom', 'url' => $id_or_url, 'audio' => $audio, 'title' => $title], $optional_values);
default:
Console::warning(zm_internal_errcode('E00035') . "传入的music type({$type})错误!");
logger()->warning(zm_internal_errcode('E00035') . "传入的music type({$type})错误!");
return ' ';
}
}
@ -419,7 +418,7 @@ class CQ
$str = '[CQ:' . $cq;
foreach ($array as $k => $v) {
if ($v === null) {
Console::warning('param ' . $k . ' cannot be set with null, empty CQ will returned!');
logger()->warning('param ' . $k . ' cannot be set with null, empty CQ will returned!');
return ' ';
}
$str .= ',' . $k . '=' . self::encode($v);

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace ZM\API;
use Closure;
use ZM\Console\Console;
use ZM\Store\LightCacheInside;
use ZM\Store\Lock\SpinLock;
use ZM\Store\ZMAtomic;
@ -65,7 +64,7 @@ trait CQAPI
}
return true;
}
Console::warning(zm_internal_errcode('E00036') . 'CQAPI send failed, websocket push error.');
logger()->warning(zm_internal_errcode('E00036') . 'CQAPI send failed, websocket push error.');
$response = [
'status' => 'failed',
'retcode' => -1000,

View File

@ -8,7 +8,6 @@ use ReflectionException;
use ReflectionMethod;
use ReflectionNamedType;
use ZM\API\ZMRobot;
use ZM\Console\Console;
class AllBotsProxy extends AbstractBotProxy
{
@ -26,7 +25,7 @@ class AllBotsProxy extends AbstractBotProxy
// 一般此情况代表用户进行嵌套代理,即 `->all()->allGroups()` 等情况
$reflection = new ReflectionMethod(ZMRobot::class, $name);
if (($return = $reflection->getReturnType()) && $return instanceof ReflectionNamedType && str_contains($return->getName(), 'Proxy')) {
Console::debug("Trying to construct proxy {$name} inside proxy, returning nested proxy.");
logger()->debug("Trying to construct proxy {$name} inside proxy, returning nested proxy.");
// 插入当前代理作为第一个参数
array_unshift($arguments, $this);
return $this->bot->{$name}(...$arguments);
@ -35,7 +34,7 @@ class AllBotsProxy extends AbstractBotProxy
$result = [];
// 遍历所有机器人实例
foreach ($this->bot::getAllRobot() as $bot) {
Console::debug("Calling {$name} on bot {$bot->getSelfId()}.");
logger()->debug("Calling {$name} on bot {$bot->getSelfId()}.");
$result[$bot->getSelfId()] = $bot->{$name}(...$arguments);
}
return $result;

View File

@ -6,7 +6,6 @@ namespace ZM\API\Proxies\Bot;
use ReflectionException;
use ZM\API\ZMRobot;
use ZM\Console\Console;
class AllGroupsProxy extends AbstractBotProxy
{
@ -24,7 +23,7 @@ class AllGroupsProxy extends AbstractBotProxy
// 因为目前所有群组方法都是以 `group_id` 作为第一个参数,故以此来判断
$reflection = new \ReflectionMethod(ZMRobot::class, $name);
if (!$reflection->getNumberOfParameters() || $reflection->getParameters()[0]->getName() !== 'group_id') {
Console::warning("Trying to call non-group method {$name} on AllGroupsProxy, skipped.");
logger()->warning("Trying to call non-group method {$name} on AllGroupsProxy, skipped.");
return $this->bot->{$name}(...$arguments);
}
@ -34,7 +33,7 @@ class AllGroupsProxy extends AbstractBotProxy
foreach ($groups as $group) {
$arguments[0] = $group['group_id'];
$bot_id = implode_when_necessary($this->bot->getSelfId());
Console::debug("Calling {$name} on group {$group['group_id']} on bot {$bot_id}.");
logger()->debug("Calling {$name} on group {$group['group_id']} on bot {$bot_id}.");
// 在群组上调用方法
$result[$group['group_id']] = $this->bot->{$name}(...$arguments);
}

View File

@ -68,7 +68,7 @@ class TuringAPI
return '哎呀,我刚才有点走神了,要不一会儿换一种问题试试?';
}
$result = $api_return['results'];
// Console::info(Console::setColor(json_encode($result, 128 | 256), "green"));
// logger()->info(Console::setColor(json_encode($result, 128 | 256), "green"));
$final = '';
foreach ($result as $v) {
switch ($v['resultType']) {

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace ZM\API;
use ZM\API\Proxies\Bot as Proxies;
use ZM\Console\Console;
/**
* Class ZMRobot
@ -21,7 +20,7 @@ class ZMRobot extends OneBotV11
{
$bot = $proxy ?: $this;
$bot_id = implode_when_necessary($bot->getSelfId());
Console::debug("Constructing AllBotsProxy for ZMRobot({$bot_id})");
logger()->debug("Constructing AllBotsProxy for ZMRobot({$bot_id})");
return new Proxies\AllBotsProxy($bot);
}
@ -32,7 +31,7 @@ class ZMRobot extends OneBotV11
{
$bot = $proxy ?: $this;
$bot_id = implode_when_necessary($bot->getSelfId());
Console::debug("Constructing AllGroupsProxy for ZMRobot({$bot_id})");
logger()->debug("Constructing AllGroupsProxy for ZMRobot({$bot_id})");
return new Proxies\AllGroupsProxy($bot);
}
}

View File

@ -20,7 +20,6 @@ use ZM\Annotation\Interfaces\ErgodicAnnotation;
use ZM\Annotation\Interfaces\Level;
use ZM\Annotation\Module\Closed;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Event\EventManager;
use ZM\Exception\AnnotationException;
use ZM\Utils\Manager\RouteManager;
@ -65,7 +64,7 @@ class AnnotationParser
public function registerMods()
{
foreach ($this->path_list as $path) {
Console::debug('parsing annotation in ' . $path[0] . ':' . $path[1]);
logger()->debug('parsing annotation in ' . $path[0] . ':' . $path[1]);
$all_class = ZMUtil::getClassesPsr4($path[0], $path[1]);
$conf = ZMConfig::get('global', 'runtime')['annotation_reader_ignore'] ?? [];
@ -82,7 +81,7 @@ class AnnotationParser
AnnotationReader::addGlobalIgnoredName('mixin');
$this->reader = new DualReader(new AnnotationReader(), new AttributeReader());
foreach ($all_class as $v) {
Console::debug('正在检索 ' . $v);
logger()->debug('正在检索 ' . $v);
$reflection_class = new ReflectionClass($v);
$methods = $reflection_class->getMethods(ReflectionMethod::IS_PUBLIC);
@ -132,7 +131,7 @@ class AnnotationParser
}
if ($vs instanceof MiddlewareClass) {
// 注册中间件本身的类,标记到 middlewares 属性中
Console::debug('正在注册中间件 ' . $reflection_class->getName());
logger()->debug('正在注册中间件 ' . $reflection_class->getName());
$rs = $this->registerMiddleware($vs, $reflection_class);
$this->middlewares[$rs['name']] = $rs;
}
@ -168,7 +167,7 @@ class AnnotationParser
}
}
}
Console::debug('解析注解完毕!');
logger()->debug('解析注解完毕!');
}
public function generateAnnotationEvents(): array
@ -216,7 +215,7 @@ class AnnotationParser
public function addRegisterPath(string $path, string $indoor_name)
{
if (server()->worker_id === 0) {
Console::verbose('Add register path: ' . $path . ' => ' . $indoor_name);
logger()->debug('Add register path: ' . $path . ' => ' . $indoor_name);
}
$this->path_list[] = [$path, $indoor_name];
}

View File

@ -79,7 +79,7 @@ class PureHttpCommand extends Command
$server->on('start', function ($server) {
Process::signal(SIGINT, function () use ($server) {
echo "\r";
Console::warning('Server interrupted by keyboard.');
logger()->notice('服务器收到中断信号 SIGINT正在停止');
for ($i = 0; $i < 32; ++$i) {
$num = ZMAtomic::$atomics['request'][$i]->get();
if ($num != 0) {
@ -89,7 +89,7 @@ class PureHttpCommand extends Command
$server->shutdown();
$server->stop();
});
Console::success('Server started. Use Ctrl+C to stop.');
logger()->notice('服务器已启动,请使用 Ctrl+C 以停止。');
});
$server->start();
// return this if there was no problem running the command

View File

@ -4,7 +4,6 @@ declare(strict_types=1);
namespace ZM\Config;
use ZM\Console\Console;
use ZM\Exception\ConfigException;
use ZM\Utils\DataProvider;
@ -82,11 +81,11 @@ class ZMConfig
$head_name = array_shift($separated);
// 首先判断有没有初始化这个配置文件,因为是只读,所以是懒加载,加载第一次后缓存起来
if (!isset(self::$config[$head_name])) {
Console::debug('配置文件' . $name . ' ' . $additional_key . '没读取过,正在从文件加载 ...');
logger()->debug('配置文件' . $name . ' ' . $additional_key . '没读取过,正在从文件加载 ...');
self::$config[$head_name] = self::loadConfig($head_name);
}
// global.remote_terminal
Console::debug('根据切分来寻找子配置: ' . $name);
logger()->debug('根据切分来寻找子配置: ' . $name);
$obj = self::$config[$head_name];
foreach ($separated as $key) {
if (isset($obj[$key])) {
@ -190,7 +189,7 @@ class ZMConfig
$list = [];
$files = DataProvider::scanDirFiles(self::$path, true, true);
foreach ($files as $file) {
Console::debug('正在从目录' . self::$path . '读取配置文件 ' . $file);
logger()->debug('正在从目录' . self::$path . '读取配置文件 ' . $file);
$info = pathinfo($file);
$info['extension'] = $info['extension'] ?? '';
@ -225,7 +224,7 @@ class ZMConfig
$obj->is_env = false;
}
if (mb_strpos($info['filename'], '.') !== false) {
Console::warning('文件名 ' . $info['filename'] . ' 不合法(含有"."),请检查文件名是否合法。');
logger()->warning('文件名 ' . $info['filename'] . ' 不合法(含有"."),请检查文件名是否合法。');
continue;
}
$obj->path = realpath(self::$path . '/' . $info['dirname'] . '/' . $info['basename']);
@ -265,7 +264,7 @@ class ZMConfig
*/
private static function readConfigFromFile($filename, $ext_name)
{
Console::debug('正加载配置文件 ' . $filename);
logger()->debug('正加载配置文件 ' . $filename);
switch ($ext_name) {
case 'php':
$r = require $filename;

View File

@ -731,6 +731,6 @@ trait ContainerTrait
*/
protected function log(string $message): void
{
Console::debug($this->getLogPrefix() . $message);
logger()->debug($this->getLogPrefix() . $message);
}
}

View File

@ -15,7 +15,6 @@ use ZM\API\ZMRobot;
use ZM\Config\ZMConfig;
use ZM\ConnectionManager\ConnectionObject;
use ZM\ConnectionManager\ManagerGM;
use ZM\Console\Console;
use ZM\Event\EventDispatcher;
use ZM\Exception\InterruptException;
use ZM\Exception\InvalidArgumentException;
@ -229,7 +228,7 @@ class Context implements ContextInterface
throw new InvalidArgumentException('协程等待参数缺失');
}
Console::debug('==== 开始等待输入 ====');
logger()->debug('==== 开始等待输入 ====');
if ($prompt != '') {
$this->reply($prompt);
}

View File

@ -9,7 +9,6 @@ declare(strict_types=1);
namespace ZM\DB;
use PDOException;
use ZM\Console\Console;
use ZM\Exception\DbException;
use ZM\MySQL\MySQLManager;
use ZM\Store\MySQL\SqlPoolStorage;
@ -89,7 +88,7 @@ class DB
if (!is_array($params)) {
$params = [$params];
}
Console::debug('MySQL: ' . $line . ' | ' . implode(', ', $params));
logger()->debug('MySQL: ' . $line . ' | ' . implode(', ', $params));
try {
if (SqlPoolStorage::$sql_pool === null) {
throw new DbException('未连接到任何数据库!');
@ -117,18 +116,18 @@ class DB
} catch (DbException $e) {
if (mb_strpos($e->getMessage(), 'has gone away') !== false) {
zm_sleep();
Console::warning('Gone away of MySQL! retrying!');
logger()->warning('Gone away of MySQL! retrying!');
return self::rawQuery($line, $params);
}
Console::warning($e->getMessage());
logger()->warning($e->getMessage());
throw $e;
} catch (PDOException $e) {
if (mb_strpos($e->getMessage(), 'has gone away') !== false) {
zm_sleep();
Console::warning('Gone away of MySQL! retrying!');
logger()->warning('Gone away of MySQL! retrying!');
return self::rawQuery($line, $params);
}
Console::warning($e->getMessage());
logger()->warning($e->getMessage());
throw new DbException($e->getMessage(), $e->getCode(), $e);
}
}

View File

@ -10,11 +10,8 @@ use Doctrine\Common\Annotations\AnnotationException;
use Error;
use Exception;
use Throwable;
use ZM\Adapters\OneBot11Adapter;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\InterruptException;
use ZM\Module\QQBot;
use ZM\Store\LightCacheInside;
use ZM\Store\Lock\SpinLock;
use ZM\Store\ZMAtomic;
@ -62,7 +59,7 @@ class EventDispatcher
$this->log = true;
}
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 开始分发事件: " . $class);
logger()->debug("[事件分发{$this->eid}] 开始分发事件: " . $class);
}
}
@ -96,7 +93,7 @@ class EventDispatcher
public function setRuleFunction(callable $rule = null): EventDispatcher
{
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 设置事件rule: " . $this->class);
logger()->debug("[事件分发{$this->eid}] 设置事件rule: " . $this->class);
}
$this->rule = $rule;
return $this;
@ -105,7 +102,7 @@ class EventDispatcher
public function setReturnFunction(callable $return_func): EventDispatcher
{
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 设置事件returnFunc: " . $this->class);
logger()->debug("[事件分发{$this->eid}] 设置事件returnFunc: " . $this->class);
}
$this->return_func = $return_func;
return $this;
@ -126,14 +123,14 @@ class EventDispatcher
// }
$this->dispatchEvent($v, $this->rule, ...$params);
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 单一对象 " . $v->class . '::' . (is_string($v->method) ? $v->method : '{closure}') . ' 分发结束。');
logger()->debug("[事件分发{$this->eid}] 单一对象 " . $v->class . '::' . (is_string($v->method) ? $v->method : '{closure}') . ' 分发结束。');
}
if ($this->status == self::STATUS_BEFORE_FAILED || $this->status == self::STATUS_RULE_FAILED) {
continue;
}
if (is_callable($this->return_func) && $this->status === self::STATUS_NORMAL) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 单一对象 " . $v->class . '::' . $v->method . ' 正在执行返回值处理函数 ...');
logger()->debug("[事件分发{$this->eid}] 单一对象 " . $v->class . '::' . $v->method . ' 正在执行返回值处理函数 ...');
}
($this->return_func)($this->store);
}
@ -167,11 +164,11 @@ class EventDispatcher
$q_f = $v->method;
if (($q_c ?? '') === '' && ($q_f instanceof Closure)) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 闭包函数的事件触发过程!");
logger()->debug("[事件分发{$this->eid}] 闭包函数的事件触发过程!");
}
if ($rule_func !== null && !$rule_func($v)) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 闭包函数下的 ruleFunc 判断为 false, 拒绝执行此方法。");
logger()->debug("[事件分发{$this->eid}] 闭包函数下的 ruleFunc 判断为 false, 拒绝执行此方法。");
}
$this->status = self::STATUS_RULE_FAILED;
return false;
@ -181,22 +178,22 @@ class EventDispatcher
return true;
}
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 正在判断 " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc ...');
logger()->debug("[事件分发{$this->eid}] 正在判断 " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc ...');
}
if ($rule_func !== null && !$rule_func($v)) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc 判断为 false, 拒绝执行此方法。');
logger()->debug("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc 判断为 false, 拒绝执行此方法。');
}
$this->status = self::STATUS_RULE_FAILED;
return false;
}
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc 为真,继续执行方法本身 ...');
logger()->debug("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法下的 ruleFunc 为真,继续执行方法本身 ...');
}
if (isset(EventManager::$middleware_map[$q_c][$q_f])) {
$middlewares = EventManager::$middleware_map[$q_c][$q_f];
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法还绑定了 Middleware' . implode(', ', array_map(function ($x) {
logger()->debug("[事件分发{$this->eid}] " . $q_c . '::' . $q_f . ' 方法还绑定了 Middleware' . implode(', ', array_map(function ($x) {
return $x->middleware;
}, $middlewares)));
}
@ -219,18 +216,18 @@ class EventDispatcher
$r[$k]->current_event = $v;
if (isset($middleware_obj['before'])) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] Middleware 存在前置事件,执行中 ...");
logger()->debug("[事件分发{$this->eid}] Middleware 存在前置事件,执行中 ...");
}
$rs = $middleware_obj['before'];
$before_result = $r[$k]->{$rs}(...$params);
if ($before_result === false) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] Middleware 前置事件为 false停止执行原事件开始执行下一事件。");
logger()->debug("[事件分发{$this->eid}] Middleware 前置事件为 false停止执行原事件开始执行下一事件。");
}
break;
}
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] Middleware 前置事件为 true继续执行原事件。");
logger()->debug("[事件分发{$this->eid}] Middleware 前置事件为 true继续执行原事件。");
}
}
}
@ -239,18 +236,18 @@ class EventDispatcher
$q_o = ZMUtil::getModInstance($q_c);
$q_o->_running_annotation = $v;
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 正在执行方法 " . $q_c . '::' . $q_f . ' ...');
logger()->debug("[事件分发{$this->eid}] 正在执行方法 " . $q_c . '::' . $q_f . ' ...');
}
$this->store = container()->call([$q_o, $q_f], $params);
} catch (Exception $e) {
if ($e instanceof InterruptException) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 检测到事件阻断调用,正在跳出事件分发器 ...");
logger()->debug("[事件分发{$this->eid}] 检测到事件阻断调用,正在跳出事件分发器 ...");
}
throw $e;
}
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 方法 " . $q_c . '::' . $q_f . ' 执行过程中抛出了异常,正在倒序查找 Middleware 中的捕获方法 ...');
logger()->debug("[事件分发{$this->eid}] 方法 " . $q_c . '::' . $q_f . ' 执行过程中抛出了异常,正在倒序查找 Middleware 中的捕获方法 ...');
}
for ($i = count($middlewares) - 1; $i >= 0; --$i) {
$middleware_obj = EventManager::$middlewares[$middlewares[$i]->middleware];
@ -260,7 +257,7 @@ class EventDispatcher
foreach ($middleware_obj['exceptions'] as $name => $method) {
if ($e instanceof $name) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 方法 " . $q_c . '::' . $q_f . ' 的异常 ' . get_class($e) . ' 被 Middleware:' . $middlewares[$i] . ' 下的 ' . get_class($r[$i]) . '::' . $method . ' 捕获。');
logger()->debug("[事件分发{$this->eid}] 方法 " . $q_c . '::' . $q_f . ' 的异常 ' . get_class($e) . ' 被 Middleware:' . $middlewares[$i] . ' 下的 ' . get_class($r[$i]) . '::' . $method . ' 捕获。');
}
$r[$i]->{$method}($e);
self::interrupt();
@ -274,11 +271,11 @@ class EventDispatcher
$middleware_obj = EventManager::$middlewares[$middlewares[$i]->middleware];
if (isset($middleware_obj['after'], $r[$i])) {
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] Middleware 存在后置事件,执行中 ...");
logger()->debug("[事件分发{$this->eid}] Middleware 存在后置事件,执行中 ...");
}
$r[$i]->{$middleware_obj['after']}(...$params);
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] Middleware 后置事件执行完毕!");
logger()->debug("[事件分发{$this->eid}] Middleware 后置事件执行完毕!");
}
}
}
@ -291,7 +288,7 @@ class EventDispatcher
$q_o = ZMUtil::getModInstance($q_c);
$q_o->_running_annotation = $v;
if ($this->log) {
Console::verbose("[事件分发{$this->eid}] 正在执行方法 " . $q_c . '::' . $q_f . ' ...');
logger()->debug("[事件分发{$this->eid}] 正在执行方法 " . $q_c . '::' . $q_f . ' ...');
}
$this->store = container()->call([$q_o, $q_f], $params);
$this->status = self::STATUS_NORMAL;

View File

@ -32,9 +32,9 @@ class EventManager
public static function addEvent($event_name, ?AnnotationBase $event_obj)
{
if ($event_obj->method instanceof Closure) {
Console::debug("Adding event {$event_name} at @Anonymous");
logger()->debug("Adding event {$event_name} at @Anonymous");
} else {
Console::debug("Adding event {$event_name} at " . ($event_obj->class) . ':' . ($event_obj->method));
logger()->debug("Adding event {$event_name} at " . ($event_obj->class) . ':' . ($event_obj->method));
self::$event_map[$event_obj->class][$event_obj->method][] = $event_obj;
}
self::$events[$event_name][] = $event_obj;
@ -66,7 +66,7 @@ class EventManager
}
// echo server()->worker_id.PHP_EOL;
$plain_class = $vss->class;
Console::debug('Added Middleware-based timer: ' . $plain_class . ' -> ' . $vss->method);
logger()->debug('Added Middleware-based timer: ' . $plain_class . ' -> ' . $vss->method);
Timer::tick($vss->tick_ms, function () use ($vss, $dispatcher) {
set_coroutine_params([]);
if (ZMAtomic::get('stop_signal')->get() != 0) {

View File

@ -28,26 +28,26 @@ class EventMapIterator implements Iterator
#[ReturnTypeWillChange]
public function current()
{
Console::debug('从 [' . $this->offset . '] 开始获取');
logger()->debug('从 [' . $this->offset . '] 开始获取');
return EventManager::$event_map[$this->class][$this->method][$this->offset];
}
public function next(): void
{
Console::debug('下一个offset为 [' . ++$this->offset . ']');
logger()->debug('下一个offset为 [' . ++$this->offset . ']');
$this->nextToValid();
}
#[ReturnTypeWillChange]
public function key()
{
Console::debug('返回key' . $this->offset);
logger()->debug('返回key' . $this->offset);
return isset(EventManager::$event_map[$this->class][$this->method][$this->offset]) ? $this->offset : null;
}
public function valid($s = false): bool
{
Console::debug(
logger()->debug(
"[{$this->offset}] " .
($s ? 'valid' : '') . '存在:' .
(!isset(EventManager::$event_map[$this->class][$this->method][$this->offset]) ? Console::setColor('false', 'red') : ('true' .
@ -60,7 +60,7 @@ class EventMapIterator implements Iterator
public function rewind(): void
{
Console::debug('回到0');
logger()->debug('回到0');
$this->offset = 0;
$this->nextToValid();
}
@ -73,6 +73,6 @@ class EventMapIterator implements Iterator
) {
++$this->offset;
}
Console::debug('内部偏移offset为 [' . $this->offset . ']');
logger()->debug('内部偏移offset为 [' . $this->offset . ']');
}
}

View File

@ -19,7 +19,7 @@ class OnBeforeReload implements SwooleEvent
{
public function onCall(Server $server)
{
Console::info(Console::setColor('Reloading server...', 'gold'));
logger()->info(Console::setColor('Reloading server...', 'gold'));
for ($i = 0; $i < ZM_WORKER_NUM; ++$i) {
Process::kill(zm_atomic('_#worker_' . $i)->get(), SIGUSR1);
}

View File

@ -28,7 +28,7 @@ class OnClose implements SwooleEvent
public function onCall($server, $fd)
{
unset(Context::$context[Coroutine::getCid()]);
Console::debug('Calling Swoole "close" event from fd=' . $fd);
logger()->debug('Calling Swoole "close" event from fd=' . $fd);
$conn = ManagerGM::get($fd);
if ($conn === null) {
return;

View File

@ -42,7 +42,7 @@ class OnManagerStart implements SwooleEvent
public function onCall(Server $server)
{
Console::debug('Calling onManagerStart event(1)');
logger()->debug('Calling onManagerStart event(1)');
if (!Framework::$argv['disable-safe-exit']) {
SignalListener::signalManager();
}
@ -54,17 +54,17 @@ class OnManagerStart implements SwooleEvent
});
if (Framework::$argv['watch']) {
if (extension_loaded('inotify')) {
Console::info('Enabled File watcher, framework will reload automatically.');
logger()->info('Enabled File watcher, framework will reload automatically.');
$fd = inotify_init();
$this->addWatcher(DataProvider::getSourceRootDir() . '/src', $fd);
Event::add($fd, function () use ($fd) {
$r = inotify_read($fd);
Console::verbose('File updated: ' . $r[0]['name']);
logger()->debug('File updated: ' . $r[0]['name']);
ZMUtil::reload();
});
Framework::$argv['polling-watch'] = false; // 如果开启了inotify则关闭轮询热更新
} else {
Console::warning(zm_internal_errcode('E00024') . '你还没有安装或启用 inotify 扩展,将默认使用轮询检测模式开启热更新!');
logger()->warning(zm_internal_errcode('E00024') . '你还没有安装或启用 inotify 扩展,将默认使用轮询检测模式开启热更新!');
Framework::$argv['polling-watch'] = true;
}
}
@ -84,7 +84,7 @@ class OnManagerStart implements SwooleEvent
});
}
if (Framework::$argv['interact']) {
Console::info('Interact mode');
logger()->info('Interact mode');
ZMBuf::$terminal = $r = STDIN;
Event::add($r, function () use ($r) {
$fget = fgets($r);
@ -116,7 +116,7 @@ class OnManagerStart implements SwooleEvent
});
$dispatcher->dispatchEvents($server);
*/
Console::verbose('进程 Manager 已启动');
logger()->debug('进程 Manager 已启动');
}
private function addWatcher($maindir, $fd)
@ -127,7 +127,7 @@ class OnManagerStart implements SwooleEvent
}
foreach ($dir as $subdir) {
if (is_dir($maindir . '/' . $subdir)) {
Console::debug('添加监听目录:' . $maindir . '/' . $subdir);
logger()->debug('添加监听目录:' . $maindir . '/' . $subdir);
inotify_add_watch($fd, $maindir . '/' . $subdir, IN_ATTRIB | IN_ISDIR);
$this->addWatcher($maindir . '/' . $subdir, $fd);
}

View File

@ -6,7 +6,6 @@ namespace ZM\Event\SwooleEvent;
use Swoole\Process;
use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Console\Console;
use ZM\Event\SwooleEvent;
use ZM\Utils\Manager\ProcessManager;
@ -23,7 +22,7 @@ class OnManagerStop implements SwooleEvent
Process::kill($v->pid, SIGTERM);
}
}
Console::verbose('进程 Manager 已停止!');
logger()->debug('进程 Manager 已停止!');
ProcessManager::removeProcessState(ZM_PROCESS_MANAGER);
}
}

View File

@ -26,7 +26,7 @@ class OnMessage implements SwooleEvent
{
public function onCall($server, Frame $frame)
{
Console::debug('Calling Swoole "message" from fd=' . $frame->fd . ': ' . TermColor::ITALIC . $frame->data . TermColor::RESET);
logger()->debug('Calling Swoole "message" from fd=' . $frame->fd . ': ' . TermColor::ITALIC . $frame->data . TermColor::RESET);
unset(Context::$context[Coroutine::getCid()]);
$conn = ManagerGM::get($frame->fd);
set_coroutine_params(['server' => $server, 'frame' => $frame, 'connection' => $conn]);

View File

@ -29,7 +29,7 @@ class OnOpen implements SwooleEvent
{
public function onCall($server, Request $request)
{
Console::debug('Calling Swoole "open" event from fd=' . $request->fd);
logger()->debug('Calling Swoole "open" event from fd=' . $request->fd);
unset(Context::$context[Coroutine::getCid()]);
$type = strtolower($request->header['x-client-role'] ?? $request->get['type'] ?? '');
@ -38,13 +38,13 @@ class OnOpen implements SwooleEvent
if ($token instanceof Closure) {
if (!$token($access_token)) {
$server->close($request->fd);
Console::warning(zm_internal_errcode('E00018') . 'Unauthorized access_token: ' . $access_token);
logger()->warning(zm_internal_errcode('E00018') . 'Unauthorized access_token: ' . $access_token);
return;
}
} elseif (is_string($token)) {
if ($access_token !== $token && $token !== '') {
$server->close($request->fd);
Console::warning(zm_internal_errcode('E00019') . 'Unauthorized access_token: ' . $access_token);
logger()->warning(zm_internal_errcode('E00019') . 'Unauthorized access_token: ' . $access_token);
return;
}
}

View File

@ -35,7 +35,7 @@ class OnRequest implements SwooleEvent
$response->setHeader($k, $v);
}
unset(Context::$context[Coroutine::getCid()]);
Console::debug('Calling Swoole "request" event from fd=' . $request->fd);
logger()->debug('Calling Swoole "request" event from fd=' . $request->fd);
set_coroutine_params(['request' => $request, 'response' => $response]);
resolve(ContainerServicesProvider::class)->registerServices('request');
@ -83,7 +83,7 @@ class OnRequest implements SwooleEvent
// do nothing
} catch (Exception $e) {
$response->status(500);
Console::info(
logger()->info(
$request->server['remote_addr'] . ':' . $request->server['remote_port'] .
' [' . $response->getStatusCode() . '] ' . $request->server['request_uri']
);
@ -98,7 +98,7 @@ class OnRequest implements SwooleEvent
Console::log($e->getTraceAsString(), 'gray');
} catch (Error $e) {
$response->status(500);
Console::info(
logger()->info(
$request->server['remote_addr'] . ':' . $request->server['remote_port'] .
' [' . $response->getStatusCode() . '] ' . $request->server['request_uri']
);

View File

@ -8,7 +8,6 @@ namespace ZM\Event\SwooleEvent;
use Swoole\Server;
use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Console\Console;
use ZM\Event\SwooleEvent;
use ZM\Utils\DataProvider;
use ZM\Utils\Manager\ProcessManager;
@ -21,7 +20,7 @@ class OnShutdown implements SwooleEvent
{
public function onCall(Server $server)
{
Console::verbose('正在关闭 Master 进程pid=' . posix_getpid());
logger()->debug('正在关闭 Master 进程pid=' . posix_getpid());
ProcessManager::removeProcessState(ZM_PROCESS_MASTER);
if (DataProvider::scanDirFiles(_zm_pid_dir()) == []) {
rmdir(_zm_pid_dir());

View File

@ -7,7 +7,6 @@ namespace ZM\Event\SwooleEvent;
use Swoole\Server;
use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Event\SwooleEvent;
use ZM\Framework;
use ZM\Utils\Manager\ProcessManager;
@ -21,7 +20,7 @@ class OnStart implements SwooleEvent
{
public function onCall(Server $server)
{
Console::debug('Calling onStart event(1)');
logger()->debug('Calling onStart event(1)');
if (!Framework::$argv['disable-safe-exit']) {
SignalListener::signalMaster($server);
}

View File

@ -10,7 +10,6 @@ use Swoole\Coroutine;
use Swoole\Server;
use Swoole\Timer;
use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Console\Console;
use ZM\Event\SwooleEvent;
use ZM\Store\LightCacheInside;
@ -28,6 +27,6 @@ class OnWorkerExit implements SwooleEvent
Coroutine::resume($v['coroutine']);
}
}
Console::verbose('正在结束 Worker #' . $worker_id . ',进程内可能有事务在运行...');
logger()->debug('正在结束 Worker #' . $worker_id . ',进程内可能有事务在运行...');
}
}

View File

@ -50,7 +50,7 @@ class OnWorkerStart implements SwooleEvent
{
public function onCall(Server $server, int $worker_id)
{
Console::debug('Calling onWorkerStart event(1)');
logger()->debug('Calling onWorkerStart event(1)');
if (!Framework::$argv['disable-safe-exit']) {
SignalListener::signalWorker($server, $worker_id);
}
@ -79,7 +79,7 @@ class OnWorkerStart implements SwooleEvent
$server->shutdown();
});
Console::verbose("Worker #{$server->worker_id} starting");
logger()->debug("Worker #{$server->worker_id} starting");
// ZMBuf::resetCache(); //清空变量缓存
// ZMBuf::set("wait_start", []); //添加队列在workerStart运行完成前先让其他协程等待执行
@ -107,11 +107,11 @@ class OnWorkerStart implements SwooleEvent
});
$dispatcher->dispatchEvents($server, $worker_id);
if ($dispatcher->status === EventDispatcher::STATUS_NORMAL) {
Console::debug('@OnStart 执行完毕');
logger()->debug('@OnStart 执行完毕');
} else {
Console::warning('@OnStart 执行异常!');
logger()->warning('@OnStart 执行异常!');
}
Console::verbose('Worker #' . $worker_id . ' started');
logger()->debug('Worker #' . $worker_id . ' started');
$this->gatherWorkerStartStatus();
} catch (Exception $e) {
if ($e->getMessage() === 'swoole exit') {
@ -134,7 +134,7 @@ class OnWorkerStart implements SwooleEvent
ProcessManager::saveProcessState(ZM_PROCESS_TASKWORKER, $server->worker_pid, ['worker_id' => $worker_id]);
try {
$this->loadAnnotations();
Console::verbose('TaskWorker #' . $server->worker_id . ' started');
logger()->debug('TaskWorker #' . $server->worker_id . ' started');
} catch (Exception $e) {
Console::error('TaskWorker #' . $server->worker_id . ' 加载出错!停止服务!');
Console::error(zm_internal_errcode('E00030') . $e->getMessage() . "\n" . $e->getTraceAsString());
@ -159,7 +159,7 @@ class OnWorkerStart implements SwooleEvent
goto skip;
}
// 加载各个模块的注解类,以及反射
Console::debug('Mapping annotations');
logger()->debug('Mapping annotations');
$parser = new AnnotationParser();
$composer = json_decode(file_get_contents(DataProvider::getSourceRootDir() . '/composer.json'), true);
$merge = array_merge($composer['autoload']['psr-4'] ?? [], $composer['autoload-dev']['psr-4'] ?? []);
@ -182,7 +182,7 @@ class OnWorkerStart implements SwooleEvent
$list = ModuleManager::getPackedModules();
foreach ($list as $k => $v) {
if (\server()->worker_id === 0) {
Console::info('Loading packed module: ' . $k);
logger()->info('Loading packed module: ' . $k);
}
require_once $v['phar-path'];
$func = 'loader' . $v['generated-id'];
@ -195,7 +195,7 @@ class OnWorkerStart implements SwooleEvent
$list = ModuleManager::getComposerModules();
foreach ($list as $k => $v) {
if (\server()->worker_id === 0) {
Console::info('Loading composer module: ' . $k);
logger()->info('Loading composer module: ' . $k);
}
$parser->addRegisterPath($v['module-path'], $v['namespace']);
}
@ -205,7 +205,7 @@ class OnWorkerStart implements SwooleEvent
skip:
// 加载自定义的全局函数
Console::debug('Loading context class...');
logger()->debug('Loading context class...');
$context_class = ZMConfig::get('global', 'context_class');
if (!is_a($context_class, ContextInterface::class, true)) {
throw new ZMKnownException('E00032', 'Context class must implemented from ContextInterface!');
@ -215,7 +215,7 @@ class OnWorkerStart implements SwooleEvent
ZMConfig::get('global', 'modules')['onebot'] ??
['status' => true, 'single_bot_mode' => false, 'message_level' => 99999];
if ($obb_onebot['status']) {
Console::debug('OneBot support enabled, listening OneBot event(3).');
logger()->debug('OneBot support enabled, listening OneBot event(3).');
$obj = new OnMessageEvent();
$obj->connect_type = 'qq';
$obj->class = AdapterInterface::class;
@ -240,8 +240,8 @@ class OnWorkerStart implements SwooleEvent
if (isset(ZMConfig::get('global', 'sql_config')['sql_host'])) {
if (ZMConfig::get('global', 'sql_config')['sql_host'] != '') {
if (\server()->worker_id === 0) {
Console::warning("使用 'sql_config' 配置项和 DB 数据库查询构造器进行查询数据库可能会在下一个大版本中废弃,请使用 'mysql_config' 搭配 doctrine dbal 使用!");
Console::warning('详见: `https://framework.zhamao.xin/`');
logger()->warning("使用 'sql_config' 配置项和 DB 数据库查询构造器进行查询数据库可能会在下一个大版本中废弃,请使用 'mysql_config' 搭配 doctrine dbal 使用!");
logger()->warning('详见: `https://framework.zhamao.xin/`');
}
$origin_conf = ZMConfig::get('global', 'sql_config');
$real_conf = [
@ -263,7 +263,7 @@ class OnWorkerStart implements SwooleEvent
}
}
if (!empty($real_conf)) {
Console::info('Connecting to MySQL pool');
logger()->info('Connecting to MySQL pool');
ob_start();
phpinfo(); // 这个phpinfo是有用的不能删除
$str = ob_get_clean();
@ -305,7 +305,7 @@ class OnWorkerStart implements SwooleEvent
SpinLock::unlock('worker_start_status');
$used = round((microtime(true) - LightCacheInside::get('tmp_kv', 'start_time')) * 1000, 3);
$worker_count = \server()->setting['worker_num'];
Console::success("{$worker_count} 个工作进程成功启动,共用时 {$used} ms");
logger()->info("{$worker_count} 个工作进程成功启动,共用时 {$used} ms");
} else {
LightCacheInside::set('tmp_kv', 'worker_start_status', $ls);
SpinLock::unlock('worker_start_status');

View File

@ -7,7 +7,6 @@ namespace ZM\Event\SwooleEvent;
use Swoole\Server;
use ZM\Annotation\Swoole\SwooleHandler;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Event\SwooleEvent;
use ZM\Store\LightCache;
use ZM\Utils\Manager\ProcessManager;
@ -23,7 +22,7 @@ class OnWorkerStop implements SwooleEvent
if ($worker_id == (ZMConfig::get('global.worker_cache.worker') ?? 0)) {
LightCache::savePersistence();
}
Console::verbose(($server->taskworker ? 'Task' : '') . "Worker #{$worker_id} 已停止 (Worker 状态码: " . $server->getWorkerStatus($worker_id) . ')');
logger()->debug('{worker}#{worker_id} 已停止(状态码:{status}', ['worker' => ($server->taskworker ? 'Task' : '') . 'Worker', 'worker_id' => $worker_id, 'status' => $server->getWorkerStatus($worker_id)]);
ProcessManager::removeProcessState($server->taskworker ? ZM_PROCESS_TASKWORKER : ZM_PROCESS_WORKER, $worker_id);
}
}

View File

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace ZM\Http;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Utils\HttpUtil;
class StaticFileHandler
@ -14,7 +13,7 @@ class StaticFileHandler
{
$full_path = realpath($path . '/' . $filename);
$response = ctx()->getResponse();
Console::debug('Full path: ' . $full_path);
logger()->debug('Full path: ' . $full_path);
if ($full_path !== false) {
if (strpos($full_path, $path) !== 0) {
$response->status(403);

View File

@ -7,7 +7,6 @@ namespace ZM\Module;
use Exception;
use Phar;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\ModulePackException;
use ZM\Exception\ZMException;
use ZM\Store\LightCache;
@ -105,14 +104,14 @@ class ModulePacker
$this->filename .= '.phar';
if ($this->override) {
if (file_exists($this->filename)) {
Console::info('Overwriting ' . $this->filename);
logger()->info('Overwriting ' . $this->filename);
unlink($this->filename);
}
}
$this->phar = new Phar($this->filename);
$this->phar->startBuffering();
Console::info('模块输出文件:' . $this->filename);
logger()->info('模块输出文件:' . $this->filename);
$this->addFiles(); // 添加文件
$this->addLightCacheStore(); // 保存light-cache-store指定的项
@ -184,10 +183,10 @@ class ModulePacker
foreach ($this->module['light-cache-store'] as $v) {
$r = LightCache::get($v);
if ($r === null) {
Console::warning(zm_internal_errcode('E00045') . 'LightCache 项:' . $v . ' 不存在或值为null无法为其保存。');
logger()->warning(zm_internal_errcode('E00045') . 'LightCache 项:' . $v . ' 不存在或值为null无法为其保存。');
} else {
$store[$v] = $r;
Console::info('打包LightCache持久化项' . $v);
logger()->info('打包LightCache持久化项' . $v);
}
}
$this->phar->addFromString('light_cache_store.json', json_encode($store, 128 | 256));
@ -245,13 +244,13 @@ class ModulePacker
foreach ($this->module['zm-data-store'] as $v) {
if (is_dir($base_dir . '/' . $v)) {
$v = rtrim($v, '/');
Console::info('Adding external zm_data dir: ' . $v);
logger()->info('Adding external zm_data dir: ' . $v);
$files = DataProvider::scanDirFiles($base_dir . '/' . $v, true, true);
foreach ($files as $single) {
$this->phar->addFile($base_dir . '/' . $v . '/' . $single, 'zm_data/' . $v . '/' . $single);
}
} elseif (is_file($base_dir . '/' . $v)) {
Console::info('Add external zm_data file: ' . $v);
logger()->info('Add external zm_data file: ' . $v);
$this->phar->addFile($base_dir . '/' . $v, 'zm_data/' . $v);
} else {
throw new ModulePackException(zm_internal_errcode('E00066') . '`zmdata-store` 指定的文件或目录不存在');

View File

@ -6,7 +6,6 @@ namespace ZM\Module;
use Jelix\Version\VersionComparator;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\ModulePackException;
use ZM\Exception\ZMException;
use ZM\Store\LightCache;
@ -130,18 +129,18 @@ class ModuleUnpacker
if (isset($this->module_config['unpack']['composer-autoload-items'])) {
$autoload = $this->module_config['unpack']['composer-autoload-items'];
if (isset($autoload['psr-4'])) {
Console::info('Adding extended autoload psr-4 for composer');
logger()->info('Adding extended autoload psr-4 for composer');
$composer['autoload']['psr-4'] = isset($composer['autoload']['psr-4']) ? array_merge($composer['autoload']['psr-4'], $autoload['psr-4']) : $autoload['psr-4'];
}
if (isset($autoload['files'])) {
Console::info('Adding extended autoload file for composer');
logger()->info('Adding extended autoload file for composer');
$composer['autoload']['files'] = isset($composer['autoload']['files']) ? array_merge($composer['autoload']['files'], $autoload['files']) : $autoload['files'];
}
}
if (isset($this->module_config['composer-extend-require'])) {
foreach ($this->module_config['composer-extend-require'] as $k => $v) {
Console::info('Adding extended required composer library: ' . $k);
logger()->info('Adding extended required composer library: ' . $k);
if (!isset($composer[$k])) {
$composer[$k] = $v;
}
@ -162,10 +161,10 @@ class ModuleUnpacker
@mkdir($pathinfo['dirname'], 0755, true);
}
if (is_file($v) && $override_data !== true) {
Console::info('Skipping zm_data file (not overwriting): ' . $v);
logger()->info('Skipping zm_data file (not overwriting): ' . $v);
continue;
}
Console::info('Copying zm_data file: ' . $v);
logger()->info('Copying zm_data file: ' . $v);
if (copy($k, $v) !== true) {
throw new ModulePackException(zm_internal_errcode('E00068') . 'Cannot copy file: ' . $v);
}
@ -195,25 +194,25 @@ class ModuleUnpacker
{
if ($this->module['unpack']['global-config-override'] !== false) {
$prompt = !is_string($this->module['unpack']['global-config-override']) ? '请根据模块提供者提供的要求进行修改 global.php 中对应的配置项' : $this->module['unpack']['global-config-override'];
Console::warning('模块作者要求用户手动修改 global.php 配置文件中的项目:');
Console::warning('*' . $prompt);
logger()->warning('模块作者要求用户手动修改 global.php 配置文件中的项目:');
logger()->warning('*' . $prompt);
if (STDIN === false) { // @phpstan-ignore-line
Console::warning('检测到终端无法输入,请手动修改 global.php 配置文件中的项目');
logger()->warning('检测到终端无法输入,请手动修改 global.php 配置文件中的项目');
return;
}
echo Console::setColor('请输入修改模式y(使用vim修改)/e(自行使用其他编辑器修改后确认)/N(默认暂不修改)[y/e/N] ', 'gold');
logger()->notice('请输入修改模式y(使用vim修改)/e(自行使用其他编辑器修改后确认)/N(默认暂不修改)[y/e/N] ');
$r = strtolower(trim(fgets(STDIN)));
switch ($r) {
case 'y':
system('vim ' . escapeshellarg(DataProvider::getWorkingDir() . '/config/global.php') . ' > `tty`');
Console::info('已使用 vim 修改!');
logger()->info('已使用 vim 修改!');
break;
case 'e':
echo Console::setColor('请修改后文件点击回车即可继续 [Enter] ', 'gold');
logger()->notice('请修改后文件点击回车即可继续 [Enter] ');
fgets(STDIN);
break;
case 'n':
Console::info('暂不修改 global.php');
logger()->info('暂不修改 global.php');
break;
}
}
@ -230,10 +229,10 @@ class ModuleUnpacker
@mkdir($info['dirname'], 0755, true);
}
if (is_file($base . '/' . $v) && $override_source !== true) {
Console::info('Skipping source file (not overwriting): ' . $v);
logger()->info('Skipping source file (not overwriting): ' . $v);
continue;
}
Console::info('Releasing source file: ' . $this->module['module-root-path'] . '/' . $v);
logger()->info('Releasing source file: ' . $this->module['module-root-path'] . '/' . $v);
if (copy($origin_base . '/' . $v, $base . '/' . $v) !== true) {
throw new ModulePackException(zm_internal_errcode('E00068') . 'Cannot copy file: ' . $v);

View File

@ -57,7 +57,7 @@ class QQBot
if (isset($data['post_type'])) {
// echo TermColor::ITALIC.json_encode($data, 128|256).TermColor::RESET.PHP_EOL;
ctx()->setCache('level', $level);
// Console::debug("Calling CQ Event from fd=" . ctx()->getConnection()->getFd());
// logger()->debug("Calling CQ Event from fd=" . ctx()->getConnection()->getFd());
if ($data['post_type'] != 'meta_event') {
$r = $this->dispatchBeforeEvents($data, 'pre'); // before在这里执行元事件不执行before为减少不必要的调试日志
if ($r->store === 'block') {

View File

@ -11,7 +11,6 @@ use Doctrine\DBAL\ParameterType;
use PDO;
use PDOException;
use Swoole\Database\PDOProxy;
use ZM\Console\Console;
use ZM\Exception\DbException;
use ZM\Store\MySQL\SqlPoolStorage;
@ -22,13 +21,13 @@ class MySQLConnection implements Connection
public function __construct()
{
Console::debug('Constructing...');
logger()->debug('Constructing...');
$this->conn = SqlPoolStorage::$sql_pool->getConnection();
}
public function __destruct()
{
Console::debug('Destructing');
logger()->debug('Destructing');
SqlPoolStorage::$sql_pool->putConnection($this->conn);
}
@ -40,7 +39,7 @@ class MySQLConnection implements Connection
public function prepare($sql, $options = [])
{
try {
Console::debug('Running SQL prepare: ' . $sql);
logger()->debug('Running SQL prepare: ' . $sql);
$statement = $this->conn->prepare($sql, $options);
assert($statement !== false);
} catch (PDOException $exception) {
@ -75,7 +74,7 @@ class MySQLConnection implements Connection
public function exec($sql)
{
try {
Console::debug('Running SQL exec: ' . $sql);
logger()->debug('Running SQL exec: ' . $sql);
$statement = $this->conn->exec($sql);
assert($statement !== false);
return $statement;

View File

@ -8,13 +8,12 @@ use Doctrine\DBAL\Driver as DoctrineDriver;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\DBAL\Schema\MySqlSchemaManager;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
class MySQLDriver implements DoctrineDriver
{
public function connect(array $params, $username = null, $password = null, array $driverOptions = [])
{
Console::debug('Requiring new connection');
logger()->debug('Requiring new connection');
return new MySQLConnection();
}

View File

@ -7,7 +7,6 @@ namespace ZM\Store;
use Exception;
use Swoole\Table;
use ZM\Annotation\Swoole\OnSave;
use ZM\Console\Console;
use ZM\Event\EventDispatcher;
use ZM\Exception\LightCacheException;
use ZM\Exception\ZMException;
@ -45,7 +44,7 @@ class LightCache
}
foreach ($r as $k => $v) {
$write = self::set($k, $v);
Console::verbose('Writing LightCache: ' . $k);
logger()->debug('Writing LightCache: ' . $k);
if ($write === false) {
self::$last_error = zm_internal_errcode('E00051') . '可能是由于 Hash 冲突过多导致动态空间无法分配内存';
return false;
@ -298,7 +297,7 @@ class LightCache
$r = [];
}
foreach ($r as $k => $v) {
Console::verbose('Saving ' . $k);
logger()->debug('Saving ' . $k);
$r[$k] = self::get($k);
}
file_put_contents(self::$config['persistence_path'], json_encode($r, 64 | 128 | 256));
@ -321,7 +320,7 @@ class LightCache
self::unset($v);
}
Framework::saveFrameworkState($obj);
Console::verbose('Saved.');
logger()->debug('Saved.');
}
private static function checkExpire($key)

View File

@ -29,7 +29,7 @@ class ZMRedisPool
try {
$r = self::$pool->get()->ping('123');
if (strpos(strtolower($r), '123') !== false) {
Console::debug('成功连接redis连接池');
logger()->debug('成功连接redis连接池');
} else {
var_dump($r);
}

View File

@ -9,7 +9,6 @@ use ReflectionException;
use ReflectionMethod;
use ZM\Annotation\CQ\CommandArgument;
use ZM\Annotation\CQ\CQCommand;
use ZM\Console\Console;
use ZM\Event\EventManager;
use ZM\Store\WorkerCache;
@ -70,7 +69,7 @@ class CommandInfoUtil
if (isset($formats[$trigger])) {
$format = $formats[$trigger];
} else {
Console::warning("未知的命令触发条件:{$trigger}");
logger()->warning("未知的命令触发条件:{$trigger}");
continue;
}
foreach ($conditions as $condition) {
@ -140,7 +139,7 @@ class CommandInfoUtil
try {
$reflection = new ReflectionMethod($annotation->class, $annotation->method);
} catch (ReflectionException $e) {
Console::warning('命令 ' . $id . ' 注解解析错误:' . $e->getMessage());
logger()->warning('命令 ' . $id . ' 注解解析错误:' . $e->getMessage());
continue;
}
@ -160,7 +159,7 @@ class CommandInfoUtil
];
if (empty($command['descriptions'])) {
Console::warning("命令没有描述信息:{$id}");
logger()->warning("命令没有描述信息:{$id}");
}
// 可能的触发条件,顺序会影响命令帮助的生成结果
@ -178,7 +177,7 @@ class CommandInfoUtil
}
}
if (empty($command['triggers'])) {
Console::warning("命令没有触发条件:{$id}");
logger()->warning("命令没有触发条件:{$id}");
continue;
}

View File

@ -27,7 +27,7 @@ class CoroutinePool
}
go(function () use ($func, $name) {
self::$cids[$name][] = Coroutine::getCid();
// Console::debug("正在执行协程,当前协程池中有 " . count(self::$cids[$name]) . " 个正在运行的协程: ".implode(", ", self::$cids[$name]));
// logger()->debug("正在执行协程,当前协程池中有 " . count(self::$cids[$name]) . " 个正在运行的协程: ".implode(", ", self::$cids[$name]));
$func();
self::checkCids($name);
});

View File

@ -10,7 +10,6 @@ use JsonSerializable;
use RuntimeException;
use Traversable;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Exception\ConfigException;
class DataProvider
@ -104,7 +103,7 @@ class DataProvider
}
$name = $r[1];
} elseif (count($r) != 1) {
Console::warning(zm_internal_errcode('E00057') . '存储失败,文件名只能有一级目录');
logger()->warning(zm_internal_errcode('E00057') . '存储失败,文件名只能有一级目录');
return false;
} else {
$name = $r[0];
@ -164,7 +163,7 @@ class DataProvider
} elseif ($relative === false) {
$list[] = $sub_file;
} else {
Console::warning(zm_internal_errcode('E00058') . "Relative path is not generated: wrong base directory ({$relative})");
logger()->warning(zm_internal_errcode('E00058') . "Relative path is not generated: wrong base directory ({$relative})");
return false;
}
}

View File

@ -11,7 +11,6 @@ use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Http\Response;
use ZM\Utils\Manager\RouteManager;
@ -71,19 +70,19 @@ class HttpUtil
}
$work = realpath($base_dir) . '/';
if (strpos($path, $work) !== 0) {
Console::info('[403] ' . $uri);
logger()->info('[403] ' . $uri);
self::responseCodePage($response, 403);
return true;
}
if (is_dir($path)) {
if (mb_substr($uri, -1, 1) != '/') {
Console::info('[302] ' . $uri);
logger()->info('[302] ' . $uri);
$response->redirect($uri . '/', 302);
return true;
}
foreach ($base_index as $vp) {
if (is_file($path . '/' . $vp)) {
Console::info('[200] ' . $uri);
logger()->info('[200] ' . $uri);
$exp = strtolower(pathinfo($path . $vp)['extension'] ?? 'unknown');
$response->setHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream');
$response->end(file_get_contents($path . $vp));
@ -91,14 +90,14 @@ class HttpUtil
}
}
} elseif (is_file($path)) {
Console::info('[200] ' . $uri);
logger()->info('[200] ' . $uri);
$exp = strtolower(pathinfo($path)['extension'] ?? 'unknown');
$response->setHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream');
$response->end(file_get_contents($path));
return true;
}
}
Console::info('[404] ' . $uri);
logger()->info('[404] ' . $uri);
self::responseCodePage($response, 404);
return true;
}

View File

@ -42,13 +42,13 @@ class CronManager
$cron = new CronExpression($v->expression);
$cron->setMaxIterationCount($v->max_iteration_count);
$plain_class = $v->class;
Console::debug("Cron task checker starting {$plain_class}:{$v->method}, next run at {$cron->getNextRunDate()->format('Y-m-d H:i:s')}");
logger()->debug("Cron task checker starting {$plain_class}:{$v->method}, next run at {$cron->getNextRunDate()->format('Y-m-d H:i:s')}");
if ($v->check_delay_time > 60000 || $v->check_delay_time < 1000) {
Console::warning(zm_internal_errcode('E00076') . 'Delay time must be between 1000 and 60000, reset to 20000');
logger()->warning(zm_internal_errcode('E00076') . 'Delay time must be between 1000 and 60000, reset to 20000');
$v->check_delay_time = 20000;
}
} catch (InvalidArgumentException $e) {
Console::error(zm_internal_errcode('E00075') . 'Invalid cron expression or arguments, please check it!');
logger()->error(zm_internal_errcode('E00075') . 'Invalid cron expression or arguments, please check it!');
throw $e;
}
@ -59,7 +59,7 @@ class CronManager
return;
}
try {
Console::debug('Cron: ' . ($cron->isDue() ? 'true' : 'false') . ', last: ' . $cron->getPreviousRunDate()->format('Y-m-d H:i:s') . ', next: ' . $cron->getNextRunDate()->format('Y-m-d H:i:s'));
logger()->debug('Cron: ' . ($cron->isDue() ? 'true' : 'false') . ', last: ' . $cron->getPreviousRunDate()->format('Y-m-d H:i:s') . ', next: ' . $cron->getNextRunDate()->format('Y-m-d H:i:s'));
if ($cron->isDue()) {
if ($v->getStatus() === 0) {
self::startExecute($v, $dispatcher, $cron);
@ -91,18 +91,18 @@ class CronManager
*/
private static function startExecute(Cron $v, EventDispatcher $dispatcher, CronExpression $cron)
{
Console::verbose("Cron task {$v->class}:{$v->method} is due, running at " . date('Y-m-d H:i:s') . ($v->getRecordNextTime() === 0 ? '' : (', offset ' . (time() - $v->getRecordNextTime()) . 's')));
logger()->debug("Cron task {$v->class}:{$v->method} is due, running at " . date('Y-m-d H:i:s') . ($v->getRecordNextTime() === 0 ? '' : (', offset ' . (time() - $v->getRecordNextTime()) . 's')));
$v->setStatus(1);
$starttime = microtime(true);
$pre_next_time = $cron->getNextRunDate()->getTimestamp();
$dispatcher->dispatchEvent($v, null, $cron);
Console::verbose("Cron task {$v->class}:{$v->method} is done, using " . round(microtime(true) - $starttime, 3) . 's');
logger()->debug("Cron task {$v->class}:{$v->method} is done, using " . round(microtime(true) - $starttime, 3) . 's');
if ($pre_next_time !== $cron->getNextRunDate()->getTimestamp()) { // 这一步用于判断运行的Cron是否已经覆盖到下一个运行区间
if (time() + round($v->check_delay_time / 1000) >= $pre_next_time) { // 假设检测到下一个周期运行时间已经要超过了预计的时间,则警告运行超时
Console::warning(zm_internal_errcode('E00077') . 'Cron task ' . $v->class . ':' . $v->method . ' is timeout');
logger()->warning(zm_internal_errcode('E00077') . 'Cron task ' . $v->class . ':' . $v->method . ' is timeout');
}
} else {
Console::verbose('Next run at ' . date('Y-m-d H:i:s', $cron->getNextRunDate()->getTimestamp()));
logger()->debug('Next run at ' . date('Y-m-d H:i:s', $cron->getNextRunDate()->getTimestamp()));
}
$v->setRecordNextTime($pre_next_time);
$v->setStatus(2);

View File

@ -93,12 +93,12 @@ class ModuleManager
continue;
}
if (!is_file($file . '/' . $module_config['module-root-path'] . '/zm.json')) {
Console::warning(zm_internal_errcode('E00054') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法找到模块配置文件zm.json');
logger()->warning(zm_internal_errcode('E00054') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法找到模块配置文件zm.json');
continue;
}
$module_file = json_decode(file_get_contents($file . '/' . $module_config['module-root-path'] . '/zm.json'), true);
if ($module_file === null) {
Console::warning(zm_internal_errcode('E000555') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法正常读取模块配置文件zm.json');
logger()->warning(zm_internal_errcode('E000555') . '模块(插件)文件 ' . $pathinfo['basename'] . ' 无法正常读取模块配置文件zm.json');
continue;
}
$module_config['phar-path'] = $v;
@ -187,12 +187,12 @@ class ModuleManager
{
$module_root_path = realpath(DataProvider::getSourceRootDir() . '/vendor/composer/' . $v['install-path'] . '/' . $module_path);
if ($module_root_path === false) {
Console::warning(zm_internal_errcode('E00055') . '无法找到Composer发布的插件配置路径在包 `' . $v['name'] . '` 中!');
logger()->warning(zm_internal_errcode('E00055') . '无法找到Composer发布的插件配置路径在包 `' . $v['name'] . '` 中!');
return null;
}
$json = json_decode(file_get_contents($module_root_path . '/zm.json'), true);
if ($json === null) {
Console::warning(zm_internal_errcode('E00054') . 'Composer包内无法正常读取 ' . $v['name'] . ' 的内的配置文件zm.json');
logger()->warning(zm_internal_errcode('E00054') . 'Composer包内无法正常读取 ' . $v['name'] . ' 的内的配置文件zm.json');
return null;
}
if (!isset($json['name'])) {
@ -211,7 +211,7 @@ class ModuleManager
}
}
if (!isset($json['namespace'])) {
Console::warning(zm_internal_errcode('E00055') . '无法获取Composer发布的模块命名空间');
logger()->warning(zm_internal_errcode('E00055') . '无法获取Composer发布的模块命名空间');
return null;
}
return $json;

View File

@ -8,7 +8,6 @@ use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use ZM\Annotation\Http\Controller;
use ZM\Annotation\Http\RequestMapping;
use ZM\Console\Console;
use ZM\Http\StaticFileHandler;
/**
@ -37,7 +36,7 @@ class RouteManager
}
$tail = trim($vss->route, '/');
$route_name = $prefix . ($tail === '' ? '' : '/') . $tail;
Console::debug('添加路由:' . $route_name);
logger()->debug('添加路由:' . $route_name);
$route = new Route($route_name, ['_class' => $class, '_method' => $method]);
$route->setMethods($vss->request_method);
@ -48,7 +47,7 @@ class RouteManager
{
$tail = trim($route, '/');
$route_name = ($tail === '' ? '' : '/') . $tail . '/{filename}';
Console::debug('添加静态文件路由:' . $route_name);
logger()->debug('添加静态文件路由:' . $route_name);
$route = new Route($route_name, ['_class' => __CLASS__, '_method' => 'onStaticRoute'], [], compact('path'));
self::$routes->add(md5($route_name), $route);

View File

@ -6,8 +6,6 @@ declare(strict_types=1);
namespace ZM\Utils\Manager;
use ZM\Console\Console;
class TaskManager
{
/**
@ -19,7 +17,7 @@ class TaskManager
public static function runTask(string $task_name, int $timeout = -1, ...$params)
{
if (!isset(server()->setting['task_worker_num'])) {
Console::warning(zm_internal_errcode('E00056') . '未开启 TaskWorker 进程,请先修改 global 配置文件启用!');
logger()->warning(zm_internal_errcode('E00056') . '未开启 TaskWorker 进程,请先修改 global 配置文件启用!');
return false;
}
$r = server()->taskwait(['task' => $task_name, 'params' => $params], $timeout);

View File

@ -8,7 +8,6 @@ use Exception;
use Swoole\Coroutine;
use ZM\Annotation\CQ\CQCommand;
use ZM\Annotation\Swoole\OnPipeMessageEvent;
use ZM\Console\Console;
use ZM\Event\EventDispatcher;
use ZM\Event\EventManager;
use ZM\Store\LightCache;
@ -28,7 +27,7 @@ class WorkerManager
$server = server();
switch ($data['action'] ?? '') {
case 'add_short_command':
Console::verbose('Adding short command ' . $data['data'][0]);
logger()->debug('Adding short command ' . $data['data'][0]);
$obj = new CQCommand();
$obj->method = quick_reply_closure($data['data'][1]);
$obj->match = $data['data'][0];
@ -115,7 +114,7 @@ class WorkerManager
{
$obj = ['action' => $action, 'data' => $data];
if (server()->worker_id === -1 && server()->getManagerPid() != posix_getpid()) {
Console::warning(zm_internal_errcode('E00022') . 'Cannot send worker action from master or manager process!');
logger()->warning(zm_internal_errcode('E00022') . 'Cannot send worker action from master or manager process!');
return;
}
if (server()->worker_id == $worker_id) {
@ -131,7 +130,7 @@ class WorkerManager
public static function resumeAllWorkerCoroutines()
{
if (server()->worker_id === -1) {
Console::warning("Cannot call '" . __FUNCTION__ . "' in non-worker process!");
logger()->warning("Cannot call '" . __FUNCTION__ . "' in non-worker process!");
return;
}
foreach ((LightCacheInside::get('wait_api', 'wait_api') ?? []) as $v) {

View File

@ -10,7 +10,6 @@ use ZM\Annotation\CQ\CommandArgument;
use ZM\Annotation\CQ\CQCommand;
use ZM\API\CQ;
use ZM\Config\ZMConfig;
use ZM\Console\Console;
use ZM\Entity\InputArguments;
use ZM\Entity\MatchResult;
use ZM\Event\EventManager;
@ -37,7 +36,7 @@ class MessageUtil
}
$path = realpath($path);
if ($path === false) {
Console::warning(zm_internal_errcode('E00059') . '指定的路径错误不存在!');
logger()->warning(zm_internal_errcode('E00059') . '指定的路径错误不存在!');
return false;
}
$files = [];
@ -46,7 +45,7 @@ class MessageUtil
if ($v->type == 'image') {
$result = ZMRequest::downloadFile($v->params['url'], $path . '/' . $v->params['file']);
if ($result === false) {
Console::warning(zm_internal_errcode('E00060') . '图片 ' . $v->params['url'] . ' 下载失败!');
logger()->warning(zm_internal_errcode('E00060') . '图片 ' . $v->params['url'] . ' 下载失败!');
return false;
}
$files[] = $path . '/' . $v->params['file'];

View File

@ -6,11 +6,11 @@ namespace ZM\Utils;
use Swoole\Process;
use Swoole\Server;
use ZM\Console\Console;
/**
* 炸毛框架的Linux signal管理类
* Class SignalListener
*
* @since 2.5
*/
class SignalListener
@ -22,15 +22,15 @@ class SignalListener
*/
public static function signalMaster(Server $server)
{
Console::debug('Listening Master SIGINT');
logger()->debug('正在监听 Master 进程 SIGINT');
Process::signal(SIGINT, function () use ($server) {
if (zm_atomic('_int_is_reload')->get() === 1) {
zm_atomic('_int_is_reload')->set(0);
$server->reload();
} else {
echo "\r";
Console::warning('Server interrupted(SIGINT) on Master.');
Console::warning('Server will be shutdown.');
logger()->notice('Master 进程收到中断信号 SIGINT');
logger()->notice('正在停止服务器');
Process::kill($server->master_pid, SIGTERM);
}
});
@ -44,16 +44,16 @@ class SignalListener
$func = function () {
if (\server()->master_pid == \server()->manager_pid) {
echo "\r";
Console::warning('Server interrupted(SIGINT) on Manager.');
logger()->notice('Manager 进程收到中断信号 SIGINT');
swoole_timer_after(2, function () {
Process::kill(posix_getpid(), SIGTERM);
});
} else {
Console::verbose('Interrupted in manager!');
logger()->debug('Manager 已中断');
}
self::processKillerPrompt();
};
Console::debug('Listening Manager SIGINT');
logger()->debug('正在监听 Manager 进程 SIGINT');
if (version_compare(SWOOLE_VERSION, '4.6.7') >= 0) {
Process::signal(SIGINT, $func);
} elseif (extension_loaded('pcntl')) {
@ -63,21 +63,22 @@ class SignalListener
/**
* 监听Worker/TaskWorker进程的Ctrl+C
*
* @param int $worker_id 当前进程的ID
*/
public static function signalWorker(Server $server, int $worker_id)
{
Console::debug('Listening Worker #' . $worker_id . ' SIGINT');
logger()->debug('正在监听 Worker#{worker_id} 进程 SIGINT', compact('worker_id'));
Process::signal(SIGINT, function () use ($server) {
if ($server->master_pid == $server->worker_pid) { // 当Swoole以单进程模型运行的时候Worker需要监听杀死的信号
if ($server->master_pid === $server->worker_pid) { // 当Swoole以单进程模型运行的时候Worker需要监听杀死的信号
echo "\r";
Console::warning('Server interrupted(SIGINT) on Worker.');
logger()->notice('Worker 进程收到中断信号 SIGINT');
swoole_timer_after(2, function () {
Process::kill(posix_getpid(), SIGTERM);
});
self::processKillerPrompt();
}
// Console::verbose("Interrupted in worker");
// logger()->debug("Interrupted in worker");
// do nothing
});
}
@ -101,7 +102,7 @@ class SignalListener
}
} else {
echo "\r";
Console::log('再按' . (5 - self::$manager_kill_time) . '次Ctrl+C所有Worker进程就会被强制杀死', 'red');
logger()->notice('请再按 {count} 次 Ctrl+C 以强制杀死所有 Worker 进程', ['count' => 5 - self::$manager_kill_time]);
}
}
++self::$manager_kill_time;

View File

@ -43,7 +43,7 @@ class Terminal
});
$dispatcher->dispatchEvents($it);
if ($dispatcher->store !== 'none' && $cmd !== '') {
Console::info('Command not found: ' . $cmd);
logger()->info('Command not found: ' . $cmd);
return true;
}
return false;
@ -67,7 +67,7 @@ class Terminal
public static function init()
{
Console::debug('Initializing Terminal...');
logger()->debug('Initializing Terminal...');
foreach ((EventManager::$events[TerminalCommand::class] ?? []) as $v) {
if ($v->command == 'help') {
self::$default_commands = true;
@ -80,7 +80,7 @@ class Terminal
foreach ($reflection->getMethods() as $v) {
$r = $reader->getMethodAnnotation($v, TerminalCommand::class);
if ($r !== null) {
Console::debug('adding command ' . $r->command);
logger()->debug('adding command ' . $r->command);
$r->class = Terminal::class;
$r->method = $v->getName();
EventManager::addEvent(TerminalCommand::class, $r);
@ -121,7 +121,7 @@ class Terminal
echo $obj;
return;
}
Console::warning('你还没有安装 league/climate 组件,无法使用此功能!');
logger()->warning('你还没有安装 league/climate 组件,无法使用此功能!');
}
/**
@ -129,13 +129,9 @@ class Terminal
*/
public function testlog()
{
Console::log(date('[H:i:s]') . ' [L] This is normal msg. (0)');
Console::error('This is error msg. (0)');
Console::warning('This is warning msg. (1)');
Console::info('This is info msg. (2)');
Console::success('This is success msg. (2)');
Console::verbose('This is verbose msg. (3)');
Console::debug('This is debug msg. (4)');
foreach (['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'] as $level) {
logger()->log($level, 'This is a {level} message.', compact('level'));
}
}
/**
@ -157,12 +153,13 @@ class Terminal
*/
public function level(array $it)
{
$level = intval(is_numeric($it[1] ?? 99) ? ($it[1] ?? 99) : 99);
if ($level > 4 || $level < 0) {
Console::warning("Usage: 'level 0|1|2|3|4'");
} else {
Console::setLevel($level) || Console::success('Success!!');
}
logger()->warning('Sorry, this function is not available yet.');
// $level = intval(is_numeric($it[1] ?? 99) ? ($it[1] ?? 99) : 99);
// if ($level > 4 || $level < 0) {
// Console::warning("Usage: 'level 0|1|2|3|4'");
// } else {
// Console::setLevel($level) || Console::success('Success!!');
// }
}
/**
@ -182,7 +179,7 @@ class Terminal
*/
public function echoI(array $it)
{
Console::info($it[1]);
logger()->info($it[1]);
}
/**

View File

@ -5,8 +5,8 @@ declare(strict_types=1);
namespace ZM\Utils;
use Exception;
use Psr\Log\LogLevel;
use Swoole\Process;
use ZM\Console\Console;
use ZM\Framework;
use ZM\Store\Lock\SpinLock;
use ZM\Store\ZMAtomic;
@ -32,9 +32,9 @@ class ZMUtil
if (SpinLock::tryLock('_stop_signal') === false) {
return;
}
Console::warning(Console::setColor('Stopping server...', 'red'));
if (Console::getLevel() >= 4) {
Console::trace();
logger()->notice('正在停止服务器...');
if (zm_config('logging.level') === LogLevel::DEBUG) {
debug_print_backtrace();
}
ZMAtomic::get('stop_signal')->set($error_exit ? 2 : 1);
server()->shutdown();

View File

@ -246,14 +246,14 @@ function ctx(): ContextInterface
if (isset(Context::$context[$cid])) {
return ZMBuf::$context_class[$cid] ?? (ZMBuf::$context_class[$cid] = new $c_class($cid));
}
Console::debug("未找到当前协程的上下文({$cid}),正在找父进程的上下文");
logger()->debug("未找到当前协程的上下文({$cid}),正在找父进程的上下文");
while (($parent_cid = co::getPcid($cid)) !== -1) {
$cid = $parent_cid;
if (isset(Context::$context[$cid])) {
return ZMBuf::$context_class[$cid] ?? (ZMBuf::$context_class[$cid] = new $c_class($cid));
}
}
Console::warning('当前环境不是协程环境,将返回独立的非协程的容器');
logger()->warning('当前环境不是协程环境,将返回独立的非协程的容器');
return ZMBuf::$context_class[$cid] ?? (ZMBuf::$context_class[$cid] = new $c_class($cid));
}
@ -355,7 +355,7 @@ function zm_timer_tick(int $interval, callable $runnable)
{
if (zm_cid() === -1) {
return go(static function () use ($interval, $runnable) {
Console::debug('Adding extra timer tick of ' . $interval . ' ms');
logger()->debug('Adding extra timer tick of ' . $interval . ' ms');
Swoole\Timer::tick($interval, static function () use ($runnable) {
call_with_catch($runnable);
});
@ -514,13 +514,13 @@ function zm_dump($var, ...$moreVars)
/**
* 输出info日志
*
* {@link Console::info()} 一致
* {@link logger()->info()} 一致
*
* @param mixed $obj
*/
function zm_info($obj): void
{
Console::info($obj);
logger()->info($obj);
}
/**
@ -532,7 +532,7 @@ function zm_info($obj): void
*/
function zm_warning($obj): void
{
Console::warning($obj);
logger()->warning($obj);
}
/**
@ -544,31 +544,31 @@ function zm_warning($obj): void
*/
function zm_success($obj): void
{
Console::success($obj);
throw new \RuntimeException('the success level logger has been deprecated.');
}
/**
* 输出debug日志
*
* {@link Console::debug()} 一致
* {@link logger()->debug()} 一致
*
* @param mixed $obj
*/
function zm_debug($obj): void
{
Console::debug($obj);
logger()->debug($obj);
}
/**
* 输出verbose日志
*
* {@link Console::verbose()} 一致
* {@link logger()->debug()} 一致
*
* @param mixed $obj
*/
function zm_verbose($obj): void
{
Console::verbose($obj);
logger()->debug($obj);
}
/**
@ -580,7 +580,7 @@ function zm_verbose($obj): void
*/
function zm_error($obj): void
{
Console::error($obj);
logger()->error($obj);
}
/**