LoginSignup
1
2

More than 5 years have passed since last update.

[fluentd] Punycodeや日本語URIをdecodeしてBigqueryに投げるメモ

Posted at

やりたいこと

nginxなどから吐き出されたアクセスログを
Bigqueryに送る前にPunycodeやPercentEncodeされた文字列をdecodeする

なんで?

log集計する際など、encodeされたURIやpunycodeだと不便と言われたので

(開発中のサイトでは、ドメイン、サブドメイン、パーマリンクに日本語や記号が使用されているものがあります)

解決方法

  • fluentdでBigqueryに投げる際に、ruby使ってdecode
  • fluentdの組み込みプラグイン exec Output Plugin を利用
  • decodeしている部分は、下記td-agent.confの command 部分

※ Notice

  • Punycodeをdecodeするために、SimpleIDNがインストールされている必要があります
    # /opt/td-agent/embedded/bin/fluent-gem install simpleidn
  • 本記事はv0.12 (td-agent2)を対象に書いています

td-agent.conf

<source>
  type exec
  format ltsv
  time_format %Y-%m-%d %H:%M:%S %z
  command tail -f /var/log/nginx/access.log | while read l ; do echo $l | ruby -e 'require "rubygems"; require "uri"; require "simpleidn"; str=STDIN.gets; arr=str.split(/\s/); arr[4] = "uri:"+URI.decode(arr[4].gsub("uri:", "")); arr[5] = "vhost:"+SimpleIDN.to_unicode(arr[5].gsub("vhost:", "")); puts arr.join("\t")'; done
  pos_file /var/log/td-agent/access_log.pos
  tag log.nginx
</source>
<match log.nginx>
  type record_reformer
  enable_ruby true
  tag ${tag}.${time.strftime('%Y%m%d')}
</match>
<match log.nginx.**>
  type forest
  subtype copy
  <template>
    <store>
      type bigquery
      method insert

      auth_method json_key
      json_key /etc/bq/.key/gcp_key.json

      project {project ID}
      dataset {dataset}

      auto_create_table true
      table nginx_access_log_${tag_parts[-1]}

      schema_path /etc/bq/schema.json
    </store>
  </template>
</match>

参考サイト

最後に

fluentdもRubyも勉強中のため、改善点などあれば、ご指摘お願いいたします!

1
2
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
1
2