You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel环境下异常日志的规范记录方案咨询

Laravel 生产环境异常日志记录到数据库并发送邮件方案

1. 创建错误日志表迁移

运行Artisan命令生成迁移文件:

php artisan make:migration create_error_logs_table

编辑生成的迁移文件,定义包含所需字段的数据表结构:

public function up()
{
    Schema::create('error_logs', function (Blueprint $table) {
        $table->id();
        $table->string('class')->nullable(); // 异常类名
        $table->string('method')->nullable(); // 抛出异常的方法
        $table->integer('line')->nullable(); // 异常行号
        $table->text('message'); // 异常消息
        $table->longText('stack_trace'); // 完整堆栈信息
        $table->timestamps();
    });
}

执行迁移创建表:

php artisan migrate

2. 生成错误日志模型

创建对应的数据模型:

php artisan make:model ErrorLog

在模型中设置可填充字段:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ErrorLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'class',
        'method',
        'line',
        'message',
        'stack_trace',
    ];
}

3. 自定义异常处理器

修改App\Exceptions\Handler.php,通过重写report方法实现全局异常捕获、入库和邮件通知:

先导入依赖类:

use App\Models\ErrorLog;
use Illuminate\Support\Facades\Mail;
use Throwable;

重写report方法:

public function report(Throwable $exception)
{
    // 仅在生产环境执行自定义逻辑
    if (app()->environment('production')) {
        // 解析异常栈帧,提取方法信息
        $firstTrace = $exception->getTrace()[0] ?? [];
        
        // 整理错误数据
        $errorData = [
            'class' => $exception::class,
            'method' => $firstTrace['function'] ?? null,
            'line' => $exception->getLine(),
            'message' => $exception->getMessage(),
            'stack_trace' => $exception->getTraceAsString(),
        ];

        // 写入数据库
        $errorLog = ErrorLog::create($errorData);

        // 发送通知邮件
        Mail::raw(
            "新错误记录:\n\n".
            "异常类:{$errorLog->class}\n".
            "触发方法:{$errorLog->method}\n".
            "行号:{$errorLog->line}\n".
            "错误消息:{$errorLog->message}\n\n".
            "堆栈详情:\n{$errorLog->stack_trace}",
            function ($message) {
                $message->to('your-notify-email@example.com')
                        ->subject('Laravel应用生产环境新错误通知');
            }
        );
    }

    // 保留Laravel默认日志行为(可选,若不需要可删除)
    parent::report($exception);
}

4. 配置生产环境邮件

确保生产环境的.env文件中邮件配置正确,以SMTP为例:

MAIL_MAILER=smtp
MAIL_HOST=smtp.your-mail-provider.com
MAIL_PORT=587
MAIL_USERNAME=your-account@example.com
MAIL_PASSWORD=your-mail-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=your-sender-email@example.com
MAIL_FROM_NAME="${APP_NAME}"

优化建议

  • 若邮件发送耗时,可将邮件逻辑放入队列执行,避免阻塞请求:创建通知类,替换Mail::raw为Mail::to(...)->queue(new ErrorNotification($errorLog))
  • 堆栈信息可能包含敏感数据,可根据业务需求添加过滤逻辑
  • 可给error_logs表的created_at字段添加索引,提升后续查询效率

内容的提问来源于stack exchange,提问作者kayrhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:16:11