AWSで運用されている方がよくやるfluentdを使ったログのS3アップロードです。
手順ではApacheが動いているサーバと仮定して、以下ログをアップロードします。
/var/log/httpd/access_log
/var/log/httpd/error_log
/var/log/messages
前提条件
OS:AmazonLinux 2017-09
IAM Role設定済みであること。IAM Roleはインスタンスに割り当てるといいです。
バケット名:logs
IAM Role設定例
S3の特定バケット(ログ保管)へアクセスする為のポリシー。
※ バケット名は適宜書き換えのこと。
※ Sidも適当な文字列へ書き換えること。(日時などへ)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt201803121612",
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::logs/*",
"arn:aws:s3:::logs"
]
}
]
}
td-agentインストール・設定手順
インストール
wget https://td-agent-package-browser.herokuapp.com/3/redhat/6/x86_64/td-agent-3.1.1-0.el6.x86_64.rpm
その都度最新のものをダウンロード。
rpm -Uvh td-agent-3.1.1-0.el6.x86_64.rpm
設定ファイルバックアップ
cd /etc/td-agent/
cp td-agent.conf td-agent.conf.org
td-agent プラグインのインストール
/usr/sbin/td-agent-gem install fluent-plugin-s3
/usr/sbin/td-agent-gem install fluent-plugin-forest
/usr/sbin/td-agent-gem install fluent-plugin-ec2-metadata
ログディレクトリ権限変更
cd /var/log/
chmod 750 httpd/
chown root.td-agent httpd/
ls -ld httpd/
chmod 640 messages
chown root.td-agent messages
ls -ld messages
td-agent 設定ファイルの編集
vim /etc/td-agent/td-agent.conf
※本記事、最下部の設定を記載。バケット名やバケットのパスは都度変更すること。
td-agent起動
/etc/init.d/td-agent start
ログテスト
logger test
※コンソール上でバケットを確認し、ログが転送されていることを確認する。
設定ファイル (/etc/td-agent/td-agent.conf)
<source>
@type tail
path /var/log/httpd/access_log
tag httpd-access
format apache2
pos_file /tmp/td-agent/httpd-access.pos
</source>
<source>
@type tail
path /var/log/httpd/error_log
tag httpd-error
format apache_error
pos_file /tmp/td-agent/httpd-error.pos
</source>
<source>
@type tail
path /var/log/messages
tag syslog
format syslog
pos_file /tmp/td-agent/syslog.pos
</source>
<match {httpd-access,httpd-error,syslog}.**>
@type ec2_metadata
output_tag ${tagset_system}.${tagset_name}.${tag}
<record>
System ${tagset_system}
Name ${tagset_name}
</record>
</match>
<match **.{httpd-access,httpd-error,syslog}>
@type forest
subtype s3
<template>
s3_bucket logs
s3_region ap-northeast-1
path ec2-Logs
buffer_path /var/log/td-agent/buffer/${tag}
time_slice_format ${tag_parts[0]}/${hostname}/%Y/%m/%d/${tag_parts[-1]}-%Y-%m-%d-%H
jst
flush_interval 600s
flush_at_shutdown true
</template>
</match>