improve remote terminal logging

This commit is contained in:
sunxyw
2022-05-23 11:44:21 +08:00
parent fa6af88566
commit 782e668abf
3 changed files with 50 additions and 36 deletions

View File

@@ -8,12 +8,16 @@ use ZM\Logger\ConsoleLogger;
return [ return [
'level' => LogLevel::DEBUG, 'level' => LogLevel::DEBUG,
'logger' => static function (): LoggerInterface { 'logger' => static function (string $title = null): LoggerInterface {
// 在 Master 中worker_id 将不存在 if ($title) {
$worker_id = app()->has('worker_id') ? '#' . app('worker_id') : 'Master'; $title = strtoupper($title);
} else {
// 在 Master 中worker_id 将不存在
$title = app()->has('worker_id') ? '#' . app('worker_id') : 'MST';
}
$logger = new ConsoleLogger(zm_config('logging.level')); $logger = new ConsoleLogger(zm_config('logging.level'));
$logger::$format = "[%date%] [%level%] [{$worker_id}] %body%"; $logger::$format = "[%date%] [%level%] [{$title}] %body%";
$logger::$date_format = 'Y-m-d H:i:s'; $logger::$date_format = 'Y-m-d H:i:s';
// 如果你喜欢旧版的日志格式,请取消下行注释 // 如果你喜欢旧版的日志格式,请取消下行注释
// $logger::$date_format = 'm-d H:i:s'; // $logger::$date_format = 'm-d H:i:s';

View File

@@ -191,19 +191,24 @@ class Framework
'port' => 20002, 'port' => 20002,
'token' => '', 'token' => '',
]; ];
$welcome_msg = Console::setColor('Welcome! You can use `help` for usage.', 'green');
$welcome_msg = capture_output([logger('trm'), 'info'], ['欢迎使用炸毛远程终端!输入 `help` 查看帮助!']);
$motd = capture_output(function () {
$this->printMotd();
});
/** @var Port $port */ /** @var Port $port */
$port = self::$server->listen($conf['host'], $conf['port'], SWOOLE_SOCK_TCP); $port = self::$server->listen($conf['host'], $conf['port'], SWOOLE_SOCK_TCP);
$port->set([ $port->set([
'open_http_protocol' => false, 'open_http_protocol' => false,
]); ]);
$port->on('connect', function (\Swoole\Server $serv, $fd) use ($welcome_msg, $conf) { $port->on('connect', function (\Swoole\Server $serv, $fd) use ($welcome_msg, $conf, $motd) {
ManagerGM::pushConnect($fd, 'terminal'); ManagerGM::pushConnect($fd, 'terminal');
// 推送欢迎信息 // 推送欢迎信息
$serv->send($fd, file_get_contents(working_dir() . '/config/motd.txt')); $serv->send($fd, $motd);
// 要求输入令牌 // 要求输入令牌
if (!empty($conf['token'])) { if (!empty($conf['token'])) {
$serv->send($fd, 'Please input token: '); $serv->send($fd, '请输入令牌:');
} else { } else {
$serv->send($fd, $welcome_msg . "\n>>> "); $serv->send($fd, $welcome_msg . "\n>>> ");
} }
@@ -213,38 +218,36 @@ class Framework
ob_start(); ob_start();
try { try {
$arr = LightCacheInside::get('light_array', 'input_token') ?? []; $arr = LightCacheInside::get('light_array', 'input_token') ?? [];
if (empty($arr[$fd] ?? '')) { if (empty($arr[$fd] ?? '') && $conf['token'] !== '') {
if ($conf['token'] != '') { $token = trim($data);
$token = trim($data); if ($token === $conf['token']) {
if ($token === $conf['token']) { SpinLock::transaction('input_token', static function () use ($fd, $token) {
SpinLock::transaction('input_token', function () use ($fd, $token) { $arr = LightCacheInside::get('light_array', 'input_token');
$arr = LightCacheInside::get('light_array', 'input_token'); $arr[$fd] = $token;
$arr[$fd] = $token; LightCacheInside::set('light_array', 'input_token', $arr);
LightCacheInside::set('light_array', 'input_token', $arr); });
}); $serv->send($fd, capture_output([logger('trm'), 'info'], ['令牌验证成功!']));
$serv->send($fd, Console::setColor("Auth success!!\n", 'green')); $serv->send($fd, $welcome_msg . "\n>>> ");
$serv->send($fd, $welcome_msg . "\n>>> "); } else {
} else { $serv->send($fd, capture_output([logger('trm'), 'error'], ['令牌验证失败!']));
$serv->send($fd, Console::setColor("Auth failed!!\n", 'red')); $serv->close($fd);
$serv->close($fd);
}
return;
} }
return;
} }
if (trim($data) == 'exit' || trim($data) == 'q') { if (trim($data) === 'exit' || trim($data) === 'q') {
$serv->send($fd, Console::setColor("Bye!\n", 'blue')); $serv->send($fd, capture_output([logger('trm'), 'info'], ['再见!']));
$serv->close($fd); $serv->close($fd);
return; return;
} }
Terminal::executeCommand(trim($data)); Terminal::executeCommand(trim($data));
} catch (Exception $e) { } catch (Exception $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')'; $error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00009') . 'Uncaught exception ' . get_class($e) . ' when calling "open": ' . $error_msg); logger('trm')->error(zm_internal_errcode('E00009') . 'Uncaught exception ' . get_class($e) . ' when calling "open": ' . $error_msg);
Console::trace(); logger('trm')->error($e->getTraceAsString());
} catch (Error $e) { } catch (Error $e) {
$error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')'; $error_msg = $e->getMessage() . ' at ' . $e->getFile() . '(' . $e->getLine() . ')';
Console::error(zm_internal_errcode('E00009') . 'Uncaught ' . get_class($e) . ' when calling "open": ' . $error_msg); logger('trm')->error(zm_internal_errcode('E00009') . 'Uncaught ' . get_class($e) . ' when calling "open": ' . $error_msg);
Console::trace(); logger('trm')->error($e->getTraceAsString());
} }
$r = ob_get_clean(); $r = ob_get_clean();
@@ -258,7 +261,6 @@ class Framework
$port->on('close', function ($serv, $fd) { $port->on('close', function ($serv, $fd) {
ManagerGM::popConnect($fd); ManagerGM::popConnect($fd);
// echo "Client: Close.\n";
}); });
} }
@@ -278,9 +280,6 @@ class Framework
Runtime::enableCoroutine(false, SWOOLE_HOOK_ALL); Runtime::enableCoroutine(false, SWOOLE_HOOK_ALL);
} }
global $asd;
$asd = get_included_files();
// 注册 Swoole Server 的事件 // 注册 Swoole Server 的事件
$this->registerServerEvents(); $this->registerServerEvents();
@@ -571,6 +570,7 @@ class Framework
/** /**
* 更换数组键名 * 更换数组键名
*
* @param mixed $old_key * @param mixed $old_key
* @param mixed $new_key * @param mixed $new_key
*/ */

View File

@@ -788,10 +788,20 @@ function is_assoc_array(array $array): bool
/** /**
* 返回 Logger 实例 * 返回 Logger 实例
*/ */
function logger(): LoggerInterface function logger(...$args): LoggerInterface
{ {
if (!app()->has(LoggerInterface::class)) { if (!app()->has(LoggerInterface::class)) {
return zm_config('logging.logger')(); return zm_config('logging.logger')(...$args);
} }
return resolve(LoggerInterface::class); return resolve(LoggerInterface::class);
} }
/**
* 捕获输出
*/
function capture_output(callable $callback, array $args = []): string
{
ob_start();
$callback(...$args);
return ob_get_clean();
}