插件窝 干货文章 Laravel在Linux上如何做性能监控

Laravel在Linux上如何做性能监控

Laravel 监控 Prometheus bash 190    来源:    2025-05-10

Laravel 在 Linux 上的性能监控方案

作为精通 Laravel 和 Linux 的 IT 工程师,我为您提供一套全面的性能监控方案,帮助您优化 Laravel 应用在 Linux 环境下的性能表现。

一、基础系统监控

1. 使用 Linux 自带工具

  • top/htop: 实时监控系统资源使用情况 bash htop
  • vmstat: 查看内存、交换分区、CPU 等使用情况 bash vmstat 1
  • iostat: 监控磁盘 I/O bash iostat -x 1
  • netstat/ss: 网络连接监控 bash ss -tulnp

2. 使用 sysstat 工具集

# 安装
sudo apt-get install sysstat

# 查看历史数据
sar -u  # CPU
sar -r  # 内存
sar -b  # I/O

二、Laravel 专用监控方案

1. Laravel Telescope (开发环境)

composer require laravel/telescope
php artisan telescope:install
php artisan migrate

访问 /telescope 查看详细请求、查询、队列等信息

2. Laravel Horizon (生产环境队列监控)

composer require laravel/horizon
php artisan horizon:install

访问 /horizon 监控队列性能

3. Laravel Debugbar

composer require barryvdh/laravel-debugbar --dev

提供详细的请求时间、内存使用、SQL查询等信息

三、高级监控方案

1. Prometheus + Grafana

# 安装 Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v*/prometheus-*.*-amd64.tar.gz
tar xvfz prometheus-*.tar.gz
cd prometheus-*

# 配置 prometheus.yml 添加 Laravel 导出器

使用 prometheus-client-php 包导出 Laravel 指标:

comrequire promphp/prometheus_client_php

2. New Relic APM

# 安装 New Relic PHP 代理
sudo apt-get install newrelic-php5
newrelic-install install

# 配置 Laravel 集成

3. Blackfire.io

# 安装 Blackfire 探针
wget -O - https://packages.blackfire.io/gpg.key | sudo apt-key add -
echo "deb http://packages.blackfire.io/debian any main" | sudo tee /etc/apt/sources.list.d/blackfire.list
sudo apt-get update
sudo apt-get install blackfire-php

四、Nginx/PHP-FPM 监控

1. Nginx 状态监控

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

2. PHP-FPM 状态监控

; php-fpm.conf
pm.status_path = /status
location ~ ^/(status|ping)$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    allow 127.0.0.1;
    deny all;
}

五、日志分析

1. Laravel 日志

tail -f storage/logs/laravel.log

2. 使用 GoAccess 分析 Nginx 日志

goaccess /var/log/nginx/access.log --log-format=COMBINED

3. 使用 ELK Stack (Elasticsearch, Logstash, Kibana)

用于大规模日志收集和分析

六、性能优化检查点

  1. OPcache 配置检查:

    opcache.enable=1
    opcache.memory_consumption=128
    opcache.max_accelerated_files=10000
    
  2. 队列工作进程检查:

    supervisorctl status
    
  3. 数据库查询优化:

    • 使用 Laravel Debugbar 或 Telescope 识别慢查询
    • 添加适当的数据库索引
  4. 缓存检查:

    php artisan cache:clear
    php artisan config:cache
    php artisan route:cache
    php artisan view:cache
    

通过以上综合监控方案,您可以全面掌握 Laravel 应用在 Linux 服务器上的性能表现,及时发现并解决性能瓶颈问题。