Laravelのログについて「ログ、操作ログ」


Laraveのログをどう使い分けるんかって話。

```php:
use Illuminate\Support\Facades\Log;
 
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
```




    0/Log::emergency : 緊急レベルのメッセージ。システムが使用不能。
    1/Log::alert : 警告レベルのメッセージ。直ちに措置を講じる必要がある
    2/Log::critical : クリティカルな重大なメッセージ
    3/Log::error : エラーメッセージ
    4/Log::warning : 警告レベルのメッセージ
    5/Log::notice : 正常だが重大なメッセージ
    6/Log::info : インフォメーションレベルのメッセージ
    7/Log::debug : デバッグレベルのメッセージ





```php:2021_11_11_000000_create_user_logs.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_logs', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->string('route')->nullable();
            $table->string('url')->nullable();
            $table->string('method')->nullable();
            $table->integer('status')->unsigned()->nullable();
            $table->text('message')->nullable();
            $table->string('remote_addr')->nullable();
            $table->string('user_agent')->nullable();
            $table->timestamps();

            $table->index(['created_at']);
            $table->index(['user_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_logs');
    }
};

```


モデル作成


```php:Models/UserLog.php
<?php

namespace App\Models;

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

class UserLog extends Model
{
    use HasFactory;

    protected $table = 'user_logs';

    protected $fillable = [
        'user_id',
        'route',
        'url',
        'method',
        'status',
        'message',
        'remote_addr',
        'user_agent',
    ];
}

```



```php:UserLogMiddleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use \Route;
use App\Models\UserLog;

class UserLogMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {

        $response = $next($request);

        if($response instanceof \Illuminate\Http\Response) {
            $this->insertUserLog($request, $response->status());
        }

        return $response;
    }

    /**
     * 操作ログ登録処理
     *
     * @param $request
     * @param $status
     * @return void
     */
    public function insertUserLog($request, $status)
    {
        $user = $request->user();
        if ($user != null) {
            $data = [
                'user_id' => $user ? $user->id : null,
                'route' => Route::currentRouteName(),
                'url' => $request->path(),
                'method' => $request->method(),
                'status' => $status,
                'message' => count($request->toArray()) != 0 ? json_encode($request->toArray()) : null,
                'remote_addr' => $request -> ip(),
                'user_agent' => $request -> userAgent(),
            ];
    
            $userLog = new UserLog;
            $userLog->create($data);
        }        
    }
}

```



```php:Kernel.php
/**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,

            \App\Http\Middleware\UserLogMiddleware::class,
        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

```