LoginSignup
1
3

More than 1 year has passed since last update.

LaravelのログをCloudWatch Logsに投げる

Last updated at Posted at 2021-04-28

 CloudWatchFullAccess権限を持っているIAMユーザを作成

 こちらの記事を参考にしてください。作成した時に生成されたアクセスキーとシークレットアクセスキーをenvファイルに記述しましょう。あと、LOG_CHANNEL=cloudwatchとしておきましょう。

.env
LOG_CHANNEL=cloudwatch
AWS_ACCESS_KEY_ID=xxxxxxxxxxxxxxxxxxxx
AWS_SECRET_ACCESS_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxx
AWS_DEFAULT_REGION=ap-northeast-1

 ライブラリインストール

 下記のコマンドを打ちましょう。composer経由でインストールします。これをインストールすると、依存関係で
aws/aws-sdk-php、monolog/monologもインストールされます

 composer require maxbanton/cwh

コード

 まずはこのクラスを作ります。

App\Logger\CloudWatchLogger.php
<?php

namespace App\Logger;

use Aws\CloudWatchLogs\CloudWatchLogsClient;
use Maxbanton\Cwh\Handler\CloudWatch;
use Monolog\Logger;

class CloudWatchLogger
{
    /**
     * Create a custom Monolog instance.
     *
     * @param  array  $config
     * @return \Monolog\Logger
     */
    public function __invoke(array $config)
    {
        $sdkParams = $config["sdk"];
        $tags = $config["tags"] ?? [ ];
        $name = $config["name"] ?? 'cloudwatch';

        // Instantiate AWS SDK CloudWatch Logs Client
        $client = new CloudWatchLogsClient($sdkParams);

        // Log group name, will be created if none
        $groupName = config('app.name') . '-' . config('app.env');

        // Log stream name, will be created if none
        try {
            $instance_id = file_get_contents("http://169.254.169.254/latest/meta-data/instance-id"); // <- ※1
        } catch (\Exception $e) {
            $instance_id = null;
        }
        $streamName = $instance_id ?? config('app.hostname', 'localhost'); // <- ※2

        // Days to keep logs, 14 by default. Set to `null` to allow indefinite retention.
        $retentionDays = $config["retention"];

        // Instantiate handler (tags are optional)
        $handler = new CloudWatch($client, $groupName, $streamName, $retentionDays, 10000, $tags);

        // Create a log channel
        $logger = new Logger($name);
        // Set handler
        $logger->pushHandler($handler);

        return $logger;
    }

}

config/logging.php の 'channels' => [ ] に、以下を追加します。

config/logging.php
'cloudwatch' => [
            'driver' => 'custom',
            'via' => App\Logger\CloudWatchLogger::class, // <- 上で作成したロガークラス
            'sdk' => [
                'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
                'version' => 'latest',
                'credentials' => [
                    'key' => env('AWS_ACCESS_KEY_ID'),
                    'secret' => env('AWS_SECRET_ACCESS_KEY')
                ]
            ],
            'retention' => env('CLOUDWATCH_LOG_RETENTION', 7), // <- ログ保存期間(null の場合は無制限)
        ],

 実際にログを吐き出すようにしましょう。CloudWatch Logsより確認できたら完了です。

public function index()
{
        Log::error('エラーが発生しました');
}

参考文献

1
3
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
1
3