Carpe Diem

備忘録

fluentdで複数サーバのログをまとめる

概要

複数のサーバのアクセスログをAggregatorにまとめます。こうすることでログの管理が一元化されるので、ログの管理先をS3やElasticsearchに変更したりするときにAggregatorだけの対応で済みます。

環境

  • Ubuntu 14.04
  • Nginx 1.4.6
  • fluentd 0.12.12

構成

IP 名前 役割
192.168.33.100 aggregator ログをまとめる
192.168.33.101 node1 nginxのログをforward
192.168.33.102 node2 nginxのログをforward

事前準備

Vagrantfileを編集して上記構成の3台を用意します。

  config.vm.define :aggregator do |fluentd|
    fluentd.vm.network :private_network, ip: "192.168.33.100"
  end

  config.vm.define :node1 do |fluentd|
    fluentd.vm.network :private_network, ip: "192.168.33.101"
  end

  config.vm.define :node2 do |fluentd|
    fluentd.vm.network :private_network, ip: "192.168.33.102"
  end

共通

それぞれfluentdをインストールしてください。

$ curl -L https://td-toolbelt.herokuapp.com/sh/install-ubuntu-trusty-td-agent2.sh | sh

Aggregatorの設定

fluentdの設定

/etc/td-agent/td-agent.confを以下のように編集します。初期設定を全て消してから追記してください。

<source>
  @type forward
  port 24224
</source>

<match nginx.access>
  @type file
  path /var/log/td-agent/access_log
</match>

今回は簡単のためAggregatorのローカルに保存しています。

Forwarder(node1, node2)の設定

Nginxインストール

$ sudo aptitude install nginx

Nginxログのパーミッション設定

$ sudo chmod o+rx /var/log/nginx/
$ sudo chmod o+r /var/log/nginx/access.log

fluentdの設定

/etc/td-agent/td-agent.confを以下のように編集します。

<source>
  @type tail
  path /var/log/nginx/access.log
  pos_file /var/log/td-agent/nginx.access.log.pos
  format nginx
  tag nginx.access
</source>

<match nginx.access>
  @type forward
  buffer_type memory
  buffer_chunk_limit 8m
  buffer_queue_limit 64
  flush_interval 1s
  <server>
    host 192.168.33.100
    port 24224
  </server>
  <secondary>
    @type file
    path /var/log/td-agent/forward-failed
  </secondary>
</match>

secondaryディレクティブは送信先が死んだ時やネットワーク障害時にデータを破棄しないよう、ローカルに保存する設定です。

動作確認

Nginxのあるサーバを叩くと、Aggregatorの/var/log/td-agent/access_log.xxxxxxxxの形で統合されたログが吐き出されます。

2015-07-08T01:32:27+00:00    nginx.access    {"remote":"127.0.0.1","host":"-","user":"-","method":"GET","path":"/","code":"200","size":"612","referer":"-","agent":"curl/7.35.0"}
2015-07-08T01:34:13+00:00    nginx.access    {"remote":"192.168.33.1","host":"-","user":"-","method":"GET","path":"/","code":"200","size":"612","referer":"-","agent":"curl/7.37.1"}
2015-07-08T01:34:37+00:00    nginx.access    {"remote":"192.168.33.1","host":"-","user":"-","method":"GET","path":"/hoge","code":"404","size":"177","referer":"-","agent":"curl/7.37.1"}
2015-07-08T01:34:58+00:00    nginx.access    {"remote":"192.168.33.1","host":"-","user":"-","method":"GET","path":"/fuga","code":"404","size":"177","referer":"-","agent":"curl/7.37.1"}

ソース