0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

マイクロサービスアーキテクチャでは、各サービスが独立して動作するため、監視とアラート設定が非常に重要です。今回は、Laravelを使用したマイクロサービスの監視とアラート設定について記述してみます。

目次

  1. 監視の基本概念
  2. Laravelでのログ管理
  3. 監視ツールの導入
  4. アラート設定
  5. 実践プロジェクトの例

1. 監視の基本概念

監視は、システムの健全性とパフォーマンスをリアルタイムで把握するための重要なプロセスです。主な監視項目には以下が含まれます。

  • サーバーのリソース使用率(CPU、メモリ、ディスク)
  • アプリケーションのレスポンスタイムとエラーレート
  • サービス間の通信状況

2. Laravelでのログ管理

Laravelは強力なログ管理機能を提供しており、Monologを使用して多彩なログチャンネルを設定できます。

ログ設定の確認

config/logging.phpを確認し、適切なログチャンネルを設定します。

return [
    'default' => env('LOG_CHANNEL', 'stack'),

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
            'ignore_exceptions' => false,
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],
    ],
];

3. 監視ツールの導入

PrometheusとGrafanaの導入

Prometheusはオープンソースの監視システムで、Grafanaと組み合わせて視覚化することができます。

Prometheusの設定

まず、Prometheusをインストールし、設定ファイルを編集します。

prometheus.yml

global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'laravel'
    static_configs:
      - targets: ['localhost:8000']

Grafanaの設定

Grafanaをインストールし、Prometheusをデータソースとして追加します。これにより、Prometheusが収集したメトリクスを視覚化できます。

Laravelアプリケーションのメトリクス収集

PrometheusのPHPクライアントを使用して、Laravelアプリケーションからメトリクスを収集します。

composer require jimdo/prometheus_client_php

メトリクスを収集するためのミドルウェアを作成します。

app/Http/Middleware/MonitorMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Prometheus\CollectorRegistry;
use Prometheus\Storage\InMemory;
use Prometheus\RenderTextFormat;

class MonitorMiddleware
{
    protected $registry;

    public function __construct()
    {
        $this->registry = new CollectorRegistry(new InMemory());
    }

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $histogram = $this->registry->getOrRegisterHistogram('app', 'http_requests_duration_seconds', 'Duration of HTTP requests', ['method', 'endpoint']);
        $histogram->observeDuration(time() - LARAVEL_START, [request()->method(), request()->path()]);

        return $response;
    }

    public function terminate($request, $response)
    {
        $renderer = new RenderTextFormat();
        header('Content-Type: ' . RenderTextFormat::MIME_TYPE);
        echo $renderer->render($this->registry->getMetricFamilySamples());
    }
}

ミドルウェアを登録します。

app/Http/Kernel.php

protected $middlewareGroups = [
    'web' => [
        // 他のミドルウェア
        \App\Http\Middleware\MonitorMiddleware::class,
    ],
];

4. アラート設定

Prometheusのアラートマネージャー設定

Prometheusのアラートマネージャーを使用して、特定の条件が満たされた場合にアラートを送信します。

alert.rules.yml

groups:
  - name: example
    rules:
    - alert: HighErrorRate
      expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.05
      for: 5m
      labels:
        severity: critical
      annotations:
        summary: "High error rate detected"
        description: "More than 5% of requests are failing"

Prometheusの設定にアラートルールを追加します。

prometheus.yml

rule_files:
  - "alert.rules.yml"

アラートの通知設定

アラートマネージャーの設定を行い、アラートを受け取るための通知チャンネルを設定します。Slackやメールを使用できます。

alertmanager.yml

global:
  smtp_smarthost: 'smtp.example.com:587'
  smtp_from: 'alert@example.com'
  smtp_auth_username: 'user'
  smtp_auth_password: 'password'

route:
  receiver: 'email'

receivers:
  - name: 'email'
    email_configs:
    - to: 'alert@example.com'

5. 実践プロジェクトの例

プロジェクト:監視とアラートを備えたマイクロサービス

  1. LaravelアプリケーションにPrometheusミドルウェアを追加
  2. PrometheusとGrafanaを設定し、メトリクスを視覚化
  3. アラートマネージャーを設定し、異常時に通知を送信

まとめ

この記事では、Laravelを使用したマイクロサービスの監視とアラート設定について記述してみました。PrometheusとGrafanaを使用してメトリクスを収集・視覚化し、アラートマネージャーを使って異常時に通知を送信することで、システムの健全性を維持できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?