LoginSignup
91
87

More than 5 years have passed since last update.

nginxのログをLTSV形式で出力して、fluentd経由でMongoDBに保存する

Last updated at Posted at 2014-03-07

nginxのlog_formatを忘れないところにメモっておきたかったのでメモ。

nginx設定

nginx.confのhttpコンテキスト内にLTSV形式のログフォーマット定義を行う。$time_iso8601などの変数はnginx http_core_moduleのEmbedded Variablesを参照して適当に設定しています。

/etc/nginx/conf.d/log_format.confとして分離したファイルで設定して、nginx.conf内でconf.d/*.confを読み込むようにする。

/etc/nginx/conf.d/log_format.conf
log_format ltsv 'time:$time_iso8601\t'
                'remote_addr:$remote_addr\t'
                'request_method:$request_method\t'
                'request_length:$request_length\t'
                'request_uri:$request_uri\t'
                'https:$https\t'
                'uri:$uri\t'
                'query_string:$query_string\t'
                'status:$status\t'
                'bytes_sent:$bytes_sent\t'
                'body_bytes_sent:$body_bytes_sent\t'
                'referer:$http_referer\t'
                'useragent:$http_user_agent\t'
                'forwardedfor:$http_x_forwarded_for\t'
                'request_time:$request_time\t'
                'upstream_response_time:$upstream_response_time';

serverコンテキストでアクセスログを設定。フォーマットに先に定義したltsvを指定する。

/etc/nginx/sites-enabled/server.conf
access_log /var/log/nginx/access.log ltsv;

fluentd(td-agent)設定

nginxのログファイルをformatltsvとして読み込む。

/etc/td-agent/td-agent.conf
<source>
  type tail
  format ltsv  # ←これがキモ
  tag nginx.access
  path /var/log/nginx/access.log
  pos_file /var/log/td-agent/buffer/access.log.pos
</source>

アクセスログをMongoDBの server-logデータベースnginx_access_logコレクション に保存する。

/etc/td-agent/td-agent.conf
<match nginx.access>
  type copy

  <store>
    type mongo
    host 127.0.0.1
    database server-log
    collection nginx_access_log
  </store>
</match>

MongoDB上で確認

インタラクティブシェルでMongoDBの中身を見てみる。

$ mongo server-log

上記設定のデータとちょっと違うんですが、コレクションを参照するとこんな感じになります。

> db.nginx_access_log.find()
{ "_id" : ObjectId("53183789d604801cab000017"), "hostname" : "redmine", "method" : "GET", "uri" : "/ajax/i18n/en_f09b74e1e85282d6b2633c350cc58f43.js", "status" : 200, "size" : 1157, "reqtime" : 0.008, "upsttime" : 0.008, "time" : ISODate("2014-03-06T08:53:02Z") }

以上!

91
87
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
91
87