AWS CloudWatch Log ส่ง Logs จาก EC2 มาที่ CloudWatch

25 เม.ย. 2019 , 3,158 Views   , หมวดหมู่ AWS ทุกหมวดหมู่   , ป้ายกำกับ:, , ,


โดยทำได้ 3 ทางคือ

  1. A script file โดย AWS CLI commands สามารถตั้ง scheduled อย่างเช่น cron ได้
  2. เขียน applicadtion โดยใช้ CloudWatch Logs SDK หรือ API
  3. AWS CloudWatch Logs Agent

โดยตัวอย่างนี้จะทำการ ส่ง Logs จาก EC2 มาที่ CloudWatch โดยใช้ AWS CloudWatch Logs Agent

Configure IAM Role or User สำหรับ CloudWatch Logs

  • Create Policy name CWLogPolicy
    • Create Policy

    • เลือก JSON tab และใส่ JSON policy ตามโค๊ดด้านล่าง

  • Create Role name CWLogRole
    • Create Role

    • โดยเลือก EC2 Service

    • Attach Policy CWLogPolicy to Role
    • ใส่ชื่อ Role name แล้วกด Create role

Attach/Replace IAM Role to EC2

ทำตามรูปด้านล่างครับ

 

Install และ Configure CloudWatch Logs ใน EC2

ใน ec2 ของเราต้องมี Apache webserver อยู่แล้ว และเราจะดึง log ที่อยู่ใน

มาแสดงและจัดการใน CloudWatch ก่อนอื่นเราต้อง Install the awslogs package

Amazon Linux instance

  • Install the awslogs package
  • Edit the /etc/awslogs/awslogs.conf file to configure the logs to track. For more information about editing this file, see CloudWatch Logs Agent Reference.
  • By default, the /etc/awslogs/awscli.conf points to the us-east-1 region. To push your logs to a different region, edit the awscli.conf file and specify that region.
  • Start the awslogs service.

    If you are running Amazon Linux 2, start the awslogs service with the following command.

 Ubuntu Server, CentOS, or Red Hat instance

On Ubuntu, run apt-get update before running the commands below.

  •  use the following commands and follow the prompts:


    If the preceding command does not work, try the following:
  • จากนั้นระบบจะให้เรา Config ค่าต่างๆและ สามารถเข้าไปแก้ไขค่า Config เพิ่มเติมได้ที่

ทำการ Config ค่าเพิ่มเติม

Amazon Linux instance

Ubuntu Server, CentOS, or Red Hat instance

เลื่อนลงมาท้ายๆไฟล์ จะเจอค่า Config สามารถกำหนดค่าต่างๆ หรือเพิ่มไฟล์ log ที่ต้องการได้ ตัวอย่างตามโค๊ดด้านล่าง

แก้ไข region ให้ point to มาที่ region ของเรา

Amazon Linux instance

Ubuntu Server, CentOS, or Red Hat instance

ให้เปลี่ยนตรง region = region ของเรา

ทำการ Start awslogs

ใน CloudWatch Logs ก็จะเจอ Log ที่เราทำการดึงมาจาก EC2

 

ดูเพิ่มเติม

https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/QuickStartEC2Instance.html

 


ป้ายกำกับ:, , ,