1. 日志文件位置
Laravel在Debian系统中的日志文件默认存储在项目根目录的storage/logs文件夹下(如laravel.log)。可通过ls -l storage/logs命令查看日志文件列表。
2. 配置日志级别
日志级别决定了记录的日志详细程度,Laravel支持emergency(紧急)、alert(警报)、critical(严重)、error(错误)、warning(警告)、notice(通知)、info(信息)、debug(调试)等级别。
.env文件,调整LOG_LEVEL变量(如LOG_LEVEL=error仅记录错误及以上级别日志);config/logging.php文件中的default参数(如'default' => env('LOG_LEVEL', 'debug'))。3. 配置日志通道
Laravel支持多种日志通道(如single单文件、daily每日轮转、stack多通道叠加),通道配置位于config/logging.php文件中。
daily通道(推荐):'channels' => [
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14, // 保留最近14天的日志
],
],
stack通道组合多个通道:'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single', 'daily'], // 同时记录到单文件和每日轮转文件
'ignore_exceptions' => false,
],
],
设置默认通道:在.env中修改LOG_CHANNEL=daily(对应config/logging.php中的daily通道)。4. 日志轮转设置
日志轮转可避免日志文件过大,Laravel通过daily通道或logrotate工具实现。
daily通道):在config/logging.php的daily通道中配置days参数(如days=14),Laravel会自动删除超过指定天数的日志文件。logrotate):
/etc/logrotate.d/laravel配置文件;/path/to/your/laravel/storage/logs/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 640 www-data adm
}
说明:daily表示每天轮转,rotate 14保留14天日志,compress压缩旧日志,create设置新日志文件的权限(www-data为Debian默认Web用户,adm为日志组)。5. 日志文件权限管理
确保Laravel能正常写入日志文件,需设置正确的目录和文件权限:
storage和bootstrap/cache目录权限:sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 755 storage bootstrap/cache
sudo chmod -R 644 storage/logs/*.log
(注:www-data为Debian上Apache/Nginx的默认用户,adm为日志组)。6. 日志查看与监控
tail命令查看日志文件的最后几行(如tail -f storage/logs/laravel.log);grep命令查找特定关键字(如grep "error" storage/logs/laravel.log);php artisan log:list,可查看所有可用的日志通道和配置。7. 日志清理
storage/logs目录下的所有日志文件(rm -f storage/logs/*.log),或使用find命令删除指定天数的日志(如find storage/logs -type f -name "*.log" -mtime +14 -exec rm {} \;);cron任务定期清理(如每天凌晨1点清理14天前的日志):0 1 * * * find /path/to/your/laravel/storage/logs -type f -name "*.log" -mtime +14 -exec rm -f {} \;
或使用logrotate的rotate参数自动清理旧日志。