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?

【AWS】CloudWatch Logs Insights で定期的にログクエリを実行する方法(EventBridge + Lambda)

Posted at

CloudWatch Logs Insights で定期的にログクエリを実行する方法(EventBridge + Lambda)

⭐ はじめに

CloudWatch Logs Insights で特定のログを定期的にクエリして、エラー検出や定常監視を自動化したいことは多いと思います。
この記事では、EventBridge と Lambda を組み合わせて CloudWatch Logs Insights のクエリを定期実行する方法を解説します。

❓ 現状の問題

  • CloudWatch Logs Insights で仕込みなしでクエリを実行しても、定期的に再実行する機能はありません
  • Web UI の実行は人手での操作が必要

🛠️ 実装アプローチ

✅ ステップ1: CloudWatch Logs Insights でクエリを作成

fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20

これをテストして、直実行することを確認します。

📆 ステップ2: EventBridge で定期実行を設定

  1. AWS EventBridge を開く

  2. 「ルール」を作成

  3. 「スケジュール」を選択

  4. cron 式で間隔を指定

    • 例: 毎日9時に実行

      cron(0 9 * * ? *)
      
  5. ターゲットに Lambda を指定

🧪 ステップ3: Lambda で CloudWatch Insights クエリを実行

🔐 必要な IAM 権限

  • logs:StartQuery
  • logs:GetQueryResults

💻 サンプルコード (Node.js)

const AWS = require('aws-sdk');
const cloudwatchlogs = new AWS.CloudWatchLogs();

exports.handler = async (event) => {
    const logGroupName = '/aws/lambda/your-log-group';
    const queryString = `
        fields @timestamp, @message
        | filter @message like /ERROR/
        | sort @timestamp desc
        | limit 20
    `;

    const params = {
        logGroupName,
        queryString,
        startTime: Date.now() - 3600 * 1000, // 過去1時間
        endTime: Date.now(),
    };

    try {
        const { queryId } = await cloudwatchlogs.startQuery(params).promise();

        let result;
        while (true) {
            const response = await cloudwatchlogs.getQueryResults({ queryId }).promise();
            if (response.status === 'Complete') {
                result = response.results;
                break;
            }
            await new Promise(r => setTimeout(r, 1000));
        }

        console.log('Query Results:', JSON.stringify(result, null, 2));
    } catch (err) {
        console.error('Query Failed:', err);
    }
};

📊 表示まとめ

部署 実装内容
CloudWatch Logs Insights クエリを作成
EventBridge 定期実行のルールを作成(cron(0 9 * * ? *))
Lambda クエリを実行し結果を取得

🎯 おわりに

AWS の機能を組み合わせれば、CloudWatch Logs Insights も定期的な監視システムの一部として活用できます。

日次の監視や通知システムに役立てるので、ぜひ導入を検討してみてください!

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?