fluentd で Compute Engine のログを収集する

Posted: , Modified:   GoogleCloudPlatform fluentd Qiita

本稿は Qiita 投稿記事 のバックアップです.

はじめに

Google Compute Engine インスタンス上で走っている Docker コンテナの出力を Cloud Logging に集めたい。fluentdfluent-plugin-google-cloud を使うとサービスアカウントを使って認証してくれるので簡単に収集できる。

バージョンアップに伴い下記の内容は古くなっています.2015年7月28日時点の情報はこちら

fluentd コンテナの準備

reactivehub/google-fluentd-base というベースイメージがあったので,これを使うことにした.(ビルドステータスが若干不穏な感じなので別のものに変えた方が良いかもしれない.)

ログの収集設定は 公式のものを使うことにする.よって,次の設定を適当なファイル名で保存.

<source>
  type tail
  path /var/lib/docker/containers/*/*-json.log
  pos_file /var/log/fluentd-docker.pos
  time_format %Y-%m-%dT%H:%M:%S
  tag docker.*
  format json
</source>
<match docker.var.lib.docker.containers.*.*.log>
  type record_reformer
  tag docker.all

  <record>
    container_id ${tag_parts[5]}
  </record>
</match>

なお,上記の設定では最終的に docker.all というタグのレコードが用意されるが,Cloud Logging 上ではこのタグ名に対応するコレクションが作られる.

ついでに fluentd の出力も収集するために次の設定も用意した.下記の場合,gfluentd というコレクションが作られる.

<source>
  type tail
  path /var/log/google-fluentd/google-fluentd.log
  pos_file /var/log/google-fluentd.pos
  time_format %Y-%m-%dT%H:%M:%S
  tag gfluentd
</source>

続いて,reactivehub/google-fluentd-base を基にしたイメージを作成する Dockerfile を用意する.

FROM reactivehub/google-fluentd-base

RUN /opt/google-fluentd/embedded/bin/gem install fluent-plugin-record-reformer \
                                                 fluent-plugin-google-cloud
ADD *.conf /etc/google-fluentd/config.d/

fluent-plugin-google-cloud は予めインストールされているはずなのだが,なぜか再インストールしないと認証エラーとなった.

ビルドと実行

後はいつものようにビルドし,

$ docker build -t fluentd-agent .

docker のログが保存されているディレクトリをマウントしながら起動すれば良い.

$ docker run -d --name fluentd-agent -v /var/log/docker:/var/log/docker --add-host="metadata:169.254.169.254” fluentd-agent