Help us understand the problem. What is going on with this article?

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

公式ドキュメント
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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした