【nginx/fluentd/s3/athena】fluentdでs3にlogを出してathenaで分析できるようにする その2
auto scale関係で、サーバーのログがすぐ消えてしまう環境で、ログをどこかに置いておきたい場合がある。 今回は、nginxのaccess_logを、fluentdでS3にアップロードし aws athenaで分析できるようにする
【目次】
- ec2にfluentdをセットアップ
- ecからs3にファイルアップロード <- いまここ
- athenaで分析する
ecからs3にファイルアップロード
最終的な設定ファイル
"/etc/td-agent/td-agent.conf"
<source> type config_expander <config> type tail path /var/log/nginx/access.log tag nginx_${hostname}.access pos_file /var/log/td-agent/pos/nginx.access.pos format /^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^ ]*) +\S*)?" (?<code>[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)" "(?<forwarder>[^\"]*)")?/ time_format %d/%b/%Y:%H:%M:%S %z </config> </source> <filter nginx_*.access> @type record_transformer <record> host_ip ${hostname} </record> </filter> <match nginx_*.access> type forest subtype s3 <template> aws_key_id key-yade aws_sec_key key-yade s3_bucket s3-no-bucket-mei-yade s3_region ap-northeast-1 path buffer_path /var/log/td-agent/buffer/${tag} time_slice_format nginx_log/dt=%Y-%m-%d/${tag}/ec2-%Y-%m-%d-%H retry_wait 30s retry_limit 5 flush_interval 1h flush_at_shutdown true output_tag false output_time false include_time_key true include_tag_key true format_json true time_format %Y-%m-%d %H:%M:%S </template> </match>
出力されるログ athenaで取込みやすいようにjson形式
{"remote":"xxx.xxx.xxx.xxx","host":"-","user":"-","method":"GET","path":"/healthcheck.html","code":"200","size":"43","referer":"-","agent":"ELB-HealthChecker/2.0","host_name":"ip-xxx-xxx-xxx-xxx","tag":"nginx_ip-xxx-xxx-xxx-xxx.access","time":"2018-02-02 14:02:11"}
なにをやっているのか
だいたいログの整形。
よくある nginxのaccess.logをfluentdでs3にあげる設定でやると 下記のようなログの形式がでてしまう・・・ なのでathenaに入れやすい用に整形
2018-02-02T00:54:51+00:00 nginx_ip-10-0-0-121.access {"message":"10.0.60.182 - - [02/Feb/2018:00:54:51 +0000] \"GET /healthcheck.html HTTP/1.1\" 200 43 \"-\" \"ELB-HealthChecker/2.0\""}
余分なtimestampとタグを削除
output_tag false output_time false
formatを指定
format nginx
だと、errorがでてしまうので
format /^(?<remote>[^ ]*) (?<host>[^ ]*) (?<user>[^ ]*) \[(?<time>[^\]]*)\] "(?<method>\S+)(?: +(?<path>[^ ]*) +\S*)?" (?<code>[^ ]*) (?<size>[^ ]*)(?: "(?<referer>[^\"]*)" "(?<agent>[^\"]*)" "(?<forwarder>[^\"]*)")?/
timeformatも直す time_format %d/%b/%Y:%H:%M:%S %z
どのサーバーのものだったか判定するためのhost ip追加
<filter nginx_*.access> @type record_transformer <record> host_ip ${hostname} </record> </filter>
timestampの表示を整形
athene側が yyyy-mm-dd HH:MM:SSの形でしか取り込んでくれないので
include_time_key true time_format %Y-%m-%d %H:%M:%S time_field time