故障排查指南
本文档提供常见问题的诊断和解决方案,帮助开发者快速定位和解决问题。
目录
常见错误和解决方案
安装问题
Composer 依赖安装失败
症状:
composer install
Your requirements could not be resolved to an installable set of packages.可能原因:
- PHP 版本不符合要求(需要 PHP 8.2+)
- 缺少必要的 PHP 扩展
- Composer 版本过旧
解决方案:
# 检查 PHP 版本
php -v
# 检查必需的扩展
php -m | grep -E "curl|json|mbstring|pdo"
# 更新 Composer
composer self-update
# 清除缓存并重新安装
composer clear-cache
composer install --prefer-distSwoole 扩展安装失败
症状:
pecl install swoole
configure: error: Cannot find php-config可能原因:
- 缺少 PHP 开发头文件
- 没有编译工具
解决方案:
# Ubuntu/Debian
sudo apt-get install php-dev php-pear build-essential
# CentOS/RHEL
sudo yum install php-devel php-pear gcc make
# 重新安装 Swoole
pecl install swoole配置错误
容器构建失败
症状:
DI\NotFoundException: No entry or class found for 'App\Service\UserService'可能原因:
- Bean 定义缺失
- 组件扫描路径错误
- 配置类未加载
解决方案:
// 检查 src/container.php 配置
return [
'component_scan' => [
'App\\', // 确保扫描命名空间正确
],
'configuration' => [
AppConfiguration::class, // 确保配置类存在
],
];
// 检查配置类是否存在
use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
#[Configuration]
class AppConfiguration
{
#[Bean]
public function myService(): MyService
{
return new MyService();
}
}环境变量未生效
症状:
$_ENV['APP_ENV'] 为空或默认值可能原因:
.env文件路径不正确.env文件格式错误- 运行时禁用了 dotenv(
disable_dotenv => true),或.env不在 runtime 查找的路径上
解决方案:
v0.9 由 symfony/runtime + symfony/dotenv 自动加载项目根目录的 .env, 不需要再手动调用 dotenv 库(Dotenv::createImmutable(...)->load() 之类的代码可以删掉)。
# 检查 .env 文件位置(应在项目根目录)
ls -la .env
# 格式正确(无引号,KEY=VALUE)
APP_ENV=prod
APP_NAME=myapp若仍读不到,检查入口是否引入了 vendor/autoload_runtime.php, 以及 runtime 选项里是否传了 disable_dotenv => true; 另外注意 getenv() 读不到 .env 的值,请用 kuiper\helper\env() 或 $_ENV。
运行时错误
路由未找到
症状:
404 Not Found
路由 /users/{id} 无法匹配可能原因:
- 路由属性未正确使用
- 控制器未注册为组件
- 路径参数格式错误
解决方案:
use kuiper\web\attribute\Controller;
use kuiper\web\attribute\GetMapping;
use kuiper\web\controller\AbstractController;
use kuiper\web\controller\ControllerTrait;
use Psr\Http\Message\ResponseInterface;
// 确保控制器标注 #[Controller](继承 AbstractController + use ControllerTrait)
#[Controller]
class UserController extends AbstractController
{
use ControllerTrait;
// 路由路径以 / 开头;路由参数恒为 string,需要整数时自行转换
#[GetMapping('/users/{id}')]
public function get(string $id): ResponseInterface
{
return $this->json(['id' => $id]);
}
}依赖注入失败
症状:
DI\NotFoundException: No entry or class found for 'App\Contract\UserRepositoryInterface'可能原因:
- 构造函数参数类型提示缺失
- 接口没有绑定到实现
- 循环依赖
解决方案:
use App\Contract\UserRepositoryInterface;
// 确保有类型提示
class UserService
{
public function __construct(
private UserRepositoryInterface $repository // 必须有类型
) {
}
}use kuiper\di\attribute\Bean;
use kuiper\di\attribute\Configuration;
// 为接口绑定实现(Bean 名称取返回类型 UserRepositoryInterface)
#[Configuration]
class AppConfiguration
{
#[Bean]
public function userRepository(): UserRepositoryInterface
{
return new UserRepository();
}
}TIP
也可以给实现类标注 #[Component] / #[Service],由组件扫描自动注册; Bean 方法的返回类型是接口时,容器会按接口类型注入该 Bean。
模块特定问题
缓存模块问题
Redis 连接失败
症状:
Connection refused [tcp://127.0.0.1:6379]解决方案:
Redis 连接参数配置在 application.redis 键下(所有配置必须放在 application 键下):
// src/config.php
return [
'application' => [
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => null, // 如果有密码
'database' => 0,
],
],
];# 测试连接
redis-cli ping缓存键冲突
症状:不同模块的缓存数据互相覆盖
解决方案:
// 方式一:配置 application.cache.namespace(Redis 驱动会用它作为 key 前缀)
// 方式二:键中带上模块前缀,避免不同模块使用相同的 key
$cacheKey = sprintf('user:profile:%d', $userId);日志模块问题
日志文件未创建
症状:日志目录不存在或无写入权限
解决方案:
# 创建日志目录
mkdir -p logs
# 设置权限
chmod 755 logs// src/config.php:日志配置位于 application.logging 下
return [
'application' => [
'logging' => [
'path' => __DIR__ . '/../logs',
],
],
];WARNING
loggers.root.log_file / error_log_file 只能是相对 path 的文件名, 不能是绝对路径或包含 ..,否则配置校验会失败。
协程日志上下文丢失
症状:日志中的进程 ID 无法区分协程,多协程日志交叉难以排查
解决方案:
框架的 kuiper\logger\LoggerFactory 在协程启用时会自动为日志挂载 kuiper\logger\processor\CoroutineIdProcessor,无需自定义 LoggerFactory。 如需显式指定处理器,配置 application.logging.loggers.root.processors:
return [
'application' => [
'logging' => [
'loggers' => [
'root' => [
'level' => 'debug',
// 记录协程 ID(未开启协程时用 ProcessIdProcessor)
'processors' => [
\kuiper\logger\processor\CoroutineIdProcessor::class,
],
],
],
],
],
];RPC 模块问题
服务发现失败
症状:
kuiper\rpc\exception\ResolveAddressFailedException: Cannot resolve service demo:demo.DemoService:1.0可能原因:
application.rpc.service_discovery.enabled未开启- 静态地址表里没有该服务的 key(完整 key 为
namespace:name:version) - DNS 记录解析为空
解决方案:
ServiceDiscovery 中间件通过 ServiceResolverInterface(StaticServiceResolver / DnsServiceResolver)解析地址,按 application.rpc.service_discovery 配置启用:
// src/config.php:静态地址表(地址固定的场景)
return [
'application' => [
'rpc' => [
'service_discovery' => [
'enabled' => true,
'type' => 'static', // 默认 static,可选 dns
'services' => [
// 完整键为 namespace:name:version,也支持只写服务名
'user-service' => ['http://127.0.0.1:8080'],
],
],
],
],
];连接池耗尽
症状:
kuiper\swoole\exception\PoolTimeoutException: Connection pool "db-pool" timeout after 3.00s.
Active: 10, Idle: 0, Waiting: 0, Max: 10, Avg wait: 2.1300s解决方案:
use kuiper\swoole\pool\PoolConfig;
// PoolConfig 只接受关联数组(snake_case 键名),不支持命名参数
$poolConfig = new PoolConfig([
'max_connections' => 200, // 增加最大连接数
'min_connections' => 20,
'wait_timeout' => 10, // 增加获取连接的等待超时(秒)
]);Swoole 模块问题
协程死锁
症状:应用卡死,无响应
解决方案:
// 查看协程状态(协程数持续增长通常是死锁 / 泄漏信号)
var_export(\Swoole\Coroutine::stats());
// 避免在协程中长时间持有锁而不释放
// 开启协程 hook 后,stream_socket_client 等常见阻塞函数会被自动协程化内存泄漏
症状:内存持续增长
解决方案:
# 检查内存使用(可在 worker 定时器或诊断端点里打印)
php -r 'echo memory_get_usage(true), PHP_EOL, memory_get_peak_usage(true), PHP_EOL;'// 在 worker 的 Timer / Stop 回调等生命周期钩子中调用(框架没有 #[Scheduled] 定时任务能力)
gc_collect_cycles();连接本身由连接池管理:PoolConfig 的 aged_timeout(默认 300 秒)会让物理连接定期重建, 避免复用被数据库/网关断开的连接;不需要手动 flush 空闲连接。
调试技巧指南
启用调试模式
开发环境启用调试:框架通过日志级别区分调试信息,配置放在 application.logging 下:
// src/config.php
use function kuiper\helper\env;
return [
'application' => [
'logging' => [
'loggers' => [
'root' => [
// dev 环境 debug,其余 info
'level' => env('APP_ENV') === 'dev' ? 'debug' : 'info',
'console' => env('APP_ENV') === 'dev',
],
],
],
],
];查看详细错误信息:自定义错误处理器是可调用类(#[ErrorHandler] 只能标注在类上), $displayErrorDetails 由 application.web.error.display 配置控制(默认 false):
// src/config.php:开发环境显示详细错误
return [
'application' => [
'web' => [
'error' => [
'display' => true, // 生产环境务必关闭
'logging' => true,
],
],
],
];use kuiper\web\attribute\ErrorHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Throwable;
#[ErrorHandler([Throwable::class])]
class DebugErrorHandler
{
public function __construct(
private readonly ResponseFactoryInterface $responseFactory
) {
}
public function __invoke(
ServerRequestInterface $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
): ResponseInterface {
// 开发环境显示详细错误,生产环境隐藏技术细节
$payload = $displayErrorDetails
? [
'error' => get_class($exception),
'message' => $exception->getMessage(),
'file' => $exception->getFile(),
'line' => $exception->getLine(),
'trace' => $exception->getTraceAsString(),
]
: ['error' => 'Internal server error'];
$response = $this->responseFactory->createResponse(500)
->withHeader('Content-Type', 'application/json');
$response->getBody()->write((string) json_encode($payload, JSON_UNESCAPED_UNICODE));
return $response;
}
}日志分析
启用调试日志:
// src/config.php
return [
'application' => [
'logging' => [
'loggers' => [
'root' => [
'level' => 'debug', // 开发环境使用 debug
'console' => true,
],
],
],
],
];添加上下文信息:
use kuiper\di\attribute\Service;
use Psr\Log\LoggerInterface;
#[Service]
class UserService
{
public function __construct(
private LoggerInterface $logger
) {
}
public function getUser(int $id): ?User
{
$this->logger->debug('Getting user', [
'user_id' => $id,
'method' => __METHOD__,
]);
// ...
}
}断点调试
使用 Xdebug:
# 安装 Xdebug
pecl install xdebug
# 配置 php.ini
[xdebug]
zend_extension=xdebug.so
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_port=9003IDE 配置(VSCode):
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003
}
]
}性能分析工具
使用 XHProf:
# 安装 XHProf
pecl install xhprof
# 在代码中启用
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);
// 执行代码
$data = xhprof_disable();
// 分析 $data使用 Blackfire:
# 安装 Blackfire Agent
# 在代码中启用
blackfire_start();
// 执行代码
blackfire_end();请求追踪
添加请求 ID:自定义中间件实现 PSR-15 MiddlewareInterface, 再把类名注册到 application.web.middleware(框架没有 #[Middleware] 属性):
use kuiper\di\attribute\Component;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
#[Component]
class RequestIdMiddleware implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
$requestId = $request->getHeaderLine('X-Request-ID') ?: $this->generateRequestId();
$request = $request->withAttribute('request_id', $requestId);
$response = $handler->handle($request);
return $response->withHeader('X-Request-ID', $requestId);
}
private function generateRequestId(): string
{
return bin2hex(random_bytes(16));
}
}// src/config.php
return [
'application' => [
'web' => [
'middleware' => [
App\http\RequestIdMiddleware::class,
],
],
],
];使用分布式追踪:框架基于 OpenTelemetry,通过 kuiper\otel\Telemetry 的 startSpan() / endSpan() 埋点(OTEL_ENABLED=true 时生效,未启用时 startSpan() 返回 null):
use kuiper\di\attribute\Service;
use kuiper\otel\Telemetry;
#[Service]
class TracingService
{
public function __construct(
private readonly Telemetry $telemetry
) {
}
public function withSpan(string $name, callable $fn): mixed
{
$span = $this->telemetry->startSpan($name);
try {
$result = $fn();
} catch (\Throwable $e) {
$this->telemetry->endSpan($span, $e);
throw $e;
}
$this->telemetry->endSpan($span);
return $result;
}
}性能问题诊断
缓存命中率低
症状:大量请求穿透缓存到数据库
诊断:
PSR-6 / PSR-16 接口本身没有命中率统计,需要在业务侧记录命中与未命中次数:
use kuiper\di\attribute\Component;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LoggerInterface;
#[Component]
class CacheMonitor
{
private int $hits = 0;
private int $misses = 0;
public function __construct(
private CacheItemPoolInterface $cache,
private LoggerInterface $logger
) {
}
public function get(string $key): mixed
{
$item = $this->cache->getItem($key);
if ($item->isHit()) {
++$this->hits;
return $item->get();
}
++$this->misses;
return null;
}
public function logCacheStats(): void
{
$total = $this->hits + $this->misses;
$hitRate = $total > 0 ? $this->hits / $total : 0.0;
$this->logger->info('Cache stats', [
'hits' => $this->hits,
'misses' => $this->misses,
'hit_rate' => sprintf('%.2f%%', $hitRate * 100),
]);
}
}解决方案:
- 增加缓存容量
- 调整 TTL
- 优化缓存键设计
- 使用缓存预热
数据库查询慢
症状:响应时间长,数据库 CPU 高
诊断:
-- 启用慢查询日志
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
-- 查看慢查询
SELECT * FROM mysql.slow_log;使用查询分析:
use kuiper\di\attribute\Component;
use Psr\Log\LoggerInterface;
#[Component]
class QueryLogger
{
public function __construct(
private LoggerInterface $logger
) {
}
public function logQuery(string $sql, float $duration): void
{
if ($duration > 0.1) { // 超过 100ms 记录
$this->logger->warning('Slow query', [
'sql' => $sql,
'duration' => $duration,
]);
}
}
}解决方案:
- 添加索引
- 优化查询语句
- 使用查询缓存
- 分页加载大数据集
内存泄漏
症状:内存持续增长,最终 OOM
诊断:
// 检查内存使用
memory_get_usage(true);
memory_get_peak_usage(true);
// 使用 Xdebug 分析
xdebug_start_trace('/tmp/trace');
// 执行代码
xdebug_stop_trace();常见原因:
- 循环引用
- 静态数组不断增长
- 未释放的资源
- 事件监听器未移除
解决方案:
// 在 worker 生命周期钩子(如 Swoole Timer / Stop 回调)中定期清理
gc_collect_cycles();长期驻留的连接交给连接池管理:PoolConfig 的 aged_timeout(默认 300 秒) 会让物理连接定期销毁重建,过期缓存条目由 CacheItemPool 在读取时惰性淘汰。
连接池耗尽
症状:请求等待连接超时
诊断:
use kuiper\di\attribute\Component;
use kuiper\swoole\pool\PoolStatisticsInterface;
use Psr\Log\LoggerInterface;
#[Component]
class PoolMonitor
{
public function __construct(
private LoggerInterface $logger
) {
}
// 连接池实例由创建方传入(容器不保证有现成的连接池 Bean)
public function monitorPool(PoolStatisticsInterface $pool): void
{
// 一次取回全部统计:pool_name / active_connections / idle_connections /
// total_created / total_destroyed / average_wait_time / wait_count / ...
$stats = $pool->getStatistics();
$this->logger->info('Pool stats', $stats);
if ($stats['idle_connections'] < 1 && $stats['active_connections'] >= $stats['max_connections']) {
$this->logger->warning('Pool bottleneck detected', [
'active' => $stats['active_connections'],
'max' => $stats['max_connections'],
'average_wait_time' => $stats['average_wait_time'],
]);
}
}
}解决方案:
- 增加连接池大小
- 减少连接持有时间
- 使用连接复用
- 检查连接泄漏
协程阻塞
症状:Swoole 应用性能差
诊断:
use kuiper\swoole\coroutine\Coroutine;
// 查看协程数量等状态(coroutine_num 持续增长通常是协程泄漏)
var_export(\Swoole\Coroutine::stats());
// 开启一键协程化:PDO、Redis、curl、stream_socket_client 等阻塞调用
// 会被 Swoole 自动切换为协程调度(应在进程启动阶段调用)
Coroutine::setHookFlags(SWOOLE_HOOK_ALL);
Coroutine::enable();解决方案:
- 避免使用阻塞函数(开启 hook 后由 Swoole 自动协程化)
- 使用协程客户端
- 合理设置协程数量
- 监控协程调度
日志分析方法
日志级别配置
生产环境使用 INFO 级别:
// src/config.php
use function kuiper\helper\env;
return [
'application' => [
'logging' => [
'path' => __DIR__ . '/../logs',
'loggers' => [
'root' => [
// 环境变量名是 LOGGING_LEVEL
'level' => env('LOGGING_LEVEL', 'info'),
'log_file' => 'app.log', // 相对 path 的文件名
'error_log_file' => 'error.log',
],
],
],
],
];WARNING
loggers.root 只读取 level、console、log_file、error_log_file、processors 五个键, 不支持 handlers;需要自定义 Monolog Handler 时,请配置具名(非 root)日志器。
开发环境使用 DEBUG 级别:
// src/config.php
return [
'application' => [
'logging' => [
'loggers' => [
'root' => [
'level' => 'debug',
'console' => true, // 输出到 stderr
],
],
],
],
];日志过滤
按模块过滤:
use kuiper\di\attribute\Component;
use Psr\Log\LoggerInterface;
#[Component]
class ModuleLogger
{
public function __construct(
private LoggerInterface $logger
) {
}
public function logUserAction(string $action, array $context): void
{
$this->logger->info('User action', [
'module' => 'user',
'action' => $action,
...$context,
]);
}
}按请求过滤:
# 使用 grep 过滤特定请求
grep "request_id: abc123" logs/app.log
# 使用 jq 处理 JSON 日志
cat logs/app.log | jq 'select(.request_id == "abc123")'日志聚合
使用 ELK Stack:
# filebeat.yml
filebeat.inputs:
- type: log
paths:
- /var/log/kuiper/*.log
json.keys_under_root: true
output.elasticsearch:
hosts: ["localhost:9200"]使用 Loki:
# promtail-config.yml
server:
http_listen_port: 9080
positions:
filename: /tmp/positions.yaml
scrape_configs:
- job_name: kuiper
static_configs:
- targets:
- localhost
labels:
job: kuiper
__path__: /var/log/kuiper/*.log日志可视化
使用 Grafana:
# 安装 Grafana
docker run -d -p 3000:3000 grafana/grafana
# 添加 Loki 数据源
# 创建仪表板查看日志使用 Kibana:
# 安装 Kibana
docker run -d -p 5601:5601 kibana:latest
# 创建索引模式
# 创建可视化仪表板日志分析工具
使用 goaccess:
# 实时分析日志
tail -f logs/app.log | goaccess -使用 logcli:
# 查询日志
logcli query '{app="kuiper"} | line_format "{{.message}}"'
# 统计错误数量
logcli query '{app="kuiper", level="error"} | count'总结
有效的故障排查需要:
- 系统化的方法:从症状到原因,从原因到解决方案
- 合适的工具:日志、调试器、性能分析器
- 良好的监控:提前发现问题,快速定位
- 文档记录:记录问题和解决方案,避免重复踩坑