IAM Roleの設定
/etc/awslogs/awscli.conf
に秘密情報を保持して連携する方法もあるのですが、アンチパターンなので、ロールを設定してEC2に割り当てます。
IAMからロールを作成
ロールの作成ボタンをクリックします。

EC2にロールを割り当てたいのでEC2を選択します。

ここでは、ポリシーとしてCloudWatchLogFullAccess
をロールに設定します。

適当なロール名を設定してロールを作成します。

EC2作成時にロールを割り当てる
上記でEC2に作成したロールを割り当てます。

エージェントのインストール
先ほど作成したEC2インスタンスでエージェントをインストールします。
sudo yum install -y awslogs
設定ファイルの編集
設定ファイルを編集します。
/etc/awslogs/awscli.conf
[plugins]
cwlogs = cwlogs
[default]
region = ap-northeast-1
/etc/awslogs/awslogs.conf
参考) CloudWatch Logs エージェントのリファレンス
[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /var/log/messages
buffer_duration = 5000
log_stream_name = {instance_id}
initial_position = start_of_file
log_group_name = /var/log/messages
# 追加したセクション
[/logs/MyProject]
datetime_format = %Y-%m-%d %H:%M:%S # ログの日時フォーマット
file = /logs/MyProject/app.log # ログファイルパス
buffer_duration = 5000
encoding = utf_8
log_stream_name = {instance_id}
initial_position = start_of_file # 初期ポジション
log_group_name = /logs/MyProject
[項目の説明]
- datetime_format: ログの日時フォーマット
- file: ログファイルのパス
- buffer_duration: ログの送信間隔
- log_group_name: CloudWatch Logのロググループ名
- log_stream_name: ロググループのストリーム名
- encoding: エンコーディング
エージェントの起動
エージェントを起動します。
sudo systemctl start awslogsd
sudo systemctl enable awslogsd
ログの連携確認
手頃なログがなかったので、CLIでログを出力してみます。
# CloudWatchにログを連携できるか確認する
date '+%Y-%m-%d %H:%M:%S Message from EC2' >> /logs/MyProject/app.log
date '+%Y-%m-%d %H:%M:%S Message from EC2' >> /logs/MyProject/app.log
date '+%Y-%m-%d %H:%M:%S Message from EC2' >> /logs/MyProject/app.log
date '+%Y-%m-%d %H:%M:%S Message from EC2' >> /logs/MyProject/app.log
date '+%Y-%m-%d %H:%M:%S Message from EC2' >> /logs/MyProject/app.log
CloudWatchコンソールからログが確認できればOKです。


