在Ubuntu服务器上,通过修改Laravel项目的.env文件开启调试模式,这是最基础的调试准备。找到.env文件中的APP_DEBUG参数,将其值设置为true(APP_DEBUG=true)。开启后,Laravel会显示详细的错误页面(包括堆栈跟踪、请求参数等),帮助快速定位语法错误、未捕获异常等问题。
Laravel的日志系统基于Monolog,支持多级别日志记录(debug、info、warning、error等),日志文件默认存储在项目根目录的storage/logs文件夹中(如laravel.log)。
Log门面记录关键信息,例如:use Illuminate\Support\Facades\Log;
Log::debug('Debug信息:用户ID='.$userId); // 记录debug级别日志
Log::error('错误信息:数据库查询失败'); // 记录error级别日志
tail命令实时查看最新日志:tail -f /var/www/your-project/storage/logs/laravel.log
或使用grep过滤特定关键词(如error):grep -i "error" /var/www/your-project/storage/logs/laravel.log
.env文件中设置LOG_LEVEL参数,控制日志记录的最低级别(如LOG_LEVEL=debug会记录所有级别日志,LOG_LEVEL=error仅记录错误及以上级别)。Xdebug是PHP的调试扩展,配合IDE(如Visual Studio Code、PHPStorm)可实现断点调试,逐步执行代码并查看变量值、调用堆栈等信息。
sudo apt update
sudo apt install php-xdebug
/etc/php/8.1/apache2/php.ini或/etc/php/8.1/cli/php.ini),添加以下配置:zend_extension=xdebug.so
xdebug.mode=debug
xdebug.client_host=127.0.0.1 # IDE所在服务器IP(本地调试为127.0.0.1)
xdebug.client_port=9003 # Xdebug默认端口(需与IDE配置一致)
xdebug.start_with_request=yes # 自动启动调试(可选:trigger/yes)
保存后重启Web服务器(Apache/Nginx)和PHP-FPM(若使用):sudo systemctl restart apache2 # Apache
sudo systemctl restart php8.1-fpm # PHP-FPM
.vscode/launch.json文件,添加以下配置:{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003,
"pathMappings": {
"/var/www/your-project": "${workspaceFolder}" // 映射项目路径
}
}
]
}
127.0.0.1,端口80),然后在“Debug”设置中启用Xdebug。http://your-ubuntu-ip),当代码执行到断点时,IDE会暂停并显示变量值、调用堆栈等信息。Laravel内置了PHPUnit测试框架,可通过编写测试用例验证代码逻辑的正确性,避免手动调试的繁琐。
./vendor/bin/phpunit
tests/Feature或tests/Unit目录下创建测试类,例如测试首页返回200状态码:namespace Tests\Feature;
use Tests\TestCase;
class HomePageTest extends TestCase
{
public function testHomePageReturnsOk()
{
$response = $this->get('/');
$response->assertStatus(200); // 断言状态码为200
}
}
get、post等方法模拟HTTP请求,验证响应结果(如状态码、内容、JSON结构等)。对于生产环境或复杂问题,可通过日志分析工具监控Laravel日志,快速定位问题趋势。
logrotate工具自动分割旧日志,避免日志文件过大。创建/etc/logrotate.d/laravel配置文件,添加以下内容:/var/www/your-project/storage/logs/*.log {
daily # 每天轮转
missingok # 忽略缺失文件
rotate 14 # 保留14天日志
compress # 压缩旧日志
notifempty # 空日志不轮转
create 640 www-data adm # 新日志权限
}
tail -f命令实时查看日志,或通过grep过滤特定错误(如PDOException):grep -i "PDOException" /var/www/your-project/storage/logs/laravel.log
以上方法覆盖了Laravel项目在Ubuntu上的基础调试、交互式调试、测试验证及日志管理,可根据问题场景选择合适的方式。