2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

EC2(AmazonLinux2)のログをCoudWatch Logsに流す

Last updated at Posted at 2020-02-15

公式ドキュメント
https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/logs/QuickStartEC2Instance.html

(1) IAMロールの準備→CloudWatchFullアクセスでおk。
(2) Agentのインストール

$ sudo yum update -y
$ sudo yum install -y awslogs
$ sudo vi /etc/awslogs/awscli.conf
    # ここでregionをap-northeast-1に指定。
$ sudo vi /etc/awslogs/awslogs.conf
    # ここでCloudWatchに流したい対象のファイルを指定。
$ sudo systemctl start awslogsd
$ sudo systemctl enable awslogsd.service

awslogs.confの書き方
https://docs.aws.amazon.com/ja_jp/AmazonCloudWatch/latest/logs/AgentReference.html

リファレンス
[logstream1]
log_group_name = value
log_stream_name = value
datetime_format = value
time_zone = [LOCAL|UTC]
file = value
file_fingerprint_lines = integer | integer-integer
multi_line_start_pattern = regex | {datetime_format}
initial_position = [start_of_file | end_of_file]
encoding = [ascii|utf_8|..]
buffer_duration = integer
batch_count = integer
batch_size = integer

confファイルには複数のログストリームの定義を書くことができる。それらの区別のために、括弧[ ]にファイル内で一意な名前をつける。

検証として以下のように記述。

/etc/awslogs/awslogs.conf
[/home/ec2-user/log.txt]
datetime_format = %b %d %H:%M:%S
file = /home/ec2-user/log.txt
buffer_duration = 5000
log_stream_name = {instance_id}
initial_position = start_of_file
log_group_name = ec2_log                                                                            
test.sh
#!/bin/sh
echo "now called" >> ./log.txt

test.shを実行するたびにClowdWatchでログが見れるようになった。

image.png

なお、一度再起動した後もログが流れることが確認できた。


追記

ログファイルには日付や時刻を含めることがるため、汎用的にログストリームに流せるように改変。ワイルドカードが使える。

/etc/awslogs/awslogs.conf
[/home/ec2-user/log.txt]
datetime_format = %b %d %H:%M:%S
file = /home/ec2-user/log*.txt
buffer_duration = 5000
log_stream_name = {instance_id}
initial_position = start_of_file
log_group_name = ec2_log  

なお、ここを編集した場合は、反映させるため、以下の手順を実行。

$ sudo systemctl stop awslogsd
$ sudo systemctl start awslogsd
$ sudo systemctl enable awslogsd.service
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?