1. 系统级基础监控:掌握服务器资源状态
使用CentOS自带命令实时查看服务器核心资源占用,快速定位ThinkPHP项目运行的硬件瓶颈:
top命令实时显示CPU、内存、进程占用排名;htop(需安装:sudo yum install epel-release && sudo yum install htop)是其增强版,支持颜色标识和交互操作,更直观。vmstat 1(每秒刷新)监控虚拟内存、进程、CPU活动;iostat -x 1查看磁盘I/O负载(如读写速度、等待时间);sar -u 1收集系统活动历史数据(需安装sysstat包)。netstat -tulnp查看网络连接(端口、进程)、路由表;ss -s统计socket连接数,排查网络瓶颈。2. PHP-FPM专项监控:聚焦PHP进程状态
ThinkPHP依赖PHP-FPM处理请求,需监控其进程及性能指标:
ps aux | grep php-fpm查看PHP-FPM进程数量及资源占用;top -c按CPU排序,定位高消耗的PHP-FPM进程。/etc/php-fpm.d/www.conf),开启pm.status_path = /status;重启服务后,通过curl http://localhost/status(需配置Nginx/Apache允许访问)获取实时状态(如活跃进程数、空闲进程数、请求处理时间)。3. ThinkPHP内置工具:快速定位应用层问题
ThinkPHP提供原生性能分析工具,无需额外安装软件:
public/index.php)添加代码,开启性能分析:\think\facade\Cache::setConfig(['type' => 'file', 'path' => '/tmp/think']);
访问http://your_domain/profiler/index,查看请求耗时、内存占用、SQL执行等详细数据(数据存储在/tmp/think/profiler目录)。Log门面记录关键操作,在代码中添加:\think\facade\Log::info('用户登录成功', ['user_id' => 123]);
\think\facade\Log::error('数据库查询失败', ['sql' => $sql, 'error' => $e->getMessage()]);
日志默认存储在runtime/log目录,可通过config/log.php配置日志级别(如error、sql)和存储路径。4. 自定义中间件:定制化监控请求指标
创建中间件记录请求响应时间、内存使用,适用于需要细粒度监控的场景:
php think make:middleware PerformanceMiddleware,代码如下:namespace app\middleware;
use think\facade\Log;
class PerformanceMiddleware
{
public function handle($request, \Closure $next)
{
$start = microtime(true);
$response = $next($request);
$cost = microtime(true) - $start;
$memory = memory_get_peak_usage() / 1024 / 1024;
Log::info("请求路径: {$request->path()}, 耗时: {$cost}秒, 内存峰值: {$memory}MB");
return $response;
}
}
application/middleware.php中添加:return ['app\middleware\PerformanceMiddleware'];
所有请求都会记录耗时和内存使用,便于分析慢请求。5. 第三方APM工具:专业级全链路监控
通过专业工具实现可视化、报警、全链路追踪:
newrelic-php5扩展),配置API密钥,即可监控应用性能(如响应时间、数据库查询、错误率),并提供实时仪表盘和报警功能。prometheus.yml,添加ThinkPHP的/metrics接口(需ThinkPHP项目集成think-prometheus扩展,暴露指标数据);6. 错误与SQL监控:精准捕获异常
config/app.php,开启错误日志:'error_reporting' => E_ALL,
'error_log' => runtime/error.log',
'exception_format' => 'json',
通过Log门面捕获异常:try {
// 业务逻辑
} catch (\Exception $e) {
\think\facade\Log::error('捕获异常', ['message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
}
config/database.php中设置'log' => true),记录所有SQL语句及执行时间,便于优化慢查询。