# カスタムフォーマットを使用したログのインポート

ログがカスタムフォーマットの場合、カスタムパーサーを作成する必要があります（[手順](https://docs.fluentd.org/plugin-development#customizing-the-tail-input-plugin-parser)）。パーサーを作成したら、ファイルを */etc/td-agent/plugins/* ディレクトリに配置します。

## 一般的なパーサーの例

Treasure Dataは2つのパーサー例を提供しています：「URLパラメータ形式のキーバリューペア」と「ASCII文字区切り形式」です。どちらの形式もユーザーの間でかなり一般的です。


```
# URLパラメータ形式のキーバリューペア
last_name=smith&first_name=brian&age=22&state=CA

# ASCII文字区切り形式。この場合、区切り文字は'|'です。
# 通常、カラム名を注釈する別のファイルがあります
smith|brian|22|CA
```

- [URLパラメータ形式のキーバリューペア用カスタムパーサー](https://gist.github.com/2565478)
- [ASCII文字区切りログ用カスタムパーサー](https://gist.github.com/2565493)


既存のログをテーリングすることは、Treasure Dataを始めるための簡単な方法です。すべてをJSONとしてログに記録することをお勧めします。[理由はこちら](https://blog.treasuredata.com/blog/2012/04/26/log-everything-as-json/)。

## レコードのフィルタリング

ログをフィルタリングする必要がある場合（例：インプレッションをフィルタリングしてクリックだけを保持する）、[exec-filterプラグイン](https://docs.fluentd.org/v1.0/articles/out_exec_filter)が便利です。このプラグインは、STDINを入力、STDOUTを出力として受け取る別のスクリプトを起動し、それに応じてログをフィルタリングします。

以下は設定例です。


```conf
<source>
  type tail
  path /path/to/the/file1
  tag filter
  format json
  pos_file /var/log/td-agent/file1.pos
</source>

<match filter>
  type exec_filter
  command /usr/lib64/fluent/ruby/bin/ruby /etc/td-agent/filter.rb
  in_format json  # takes a JSON string from STDIN
  out_format json # generates a JSON string to STDOUT
  tag_key tag     # The key for tags is "tag".
  time_key time   # The key for timestamps is "time".
</match>

<match td.*.*>
  type tdlog
  endpoint api.treasuredata.com
  apikey ...
  auto_create_table
  buffer_type file
  buffer_path /var/log/td-agent/buffer/td
  use_ssl true
</match>
```

`/etc/td-agent/filter.rb` は、以下の例に示すフィルタスクリプトです。このスクリプトは、フィールド "field0" が "certain_value" と等しいすべての行をフィルタリングします。エラーは `/var/log/td-agent/filter.rb.log` に記録されます。


```ruby
open('/var/log/td-agent/filter.rb.log', 'a') { |f|
  f.puts "-- begin --"
  begin
    require 'json'
    STDOUT.sync = true
    while line = STDIN.gets
      # parse
      begin
        h = JSON.parse line
      rescue => e
        next # broken line
      end
      # filter
      # next if h["field0"] == "certain_value"
      # emit
      h['tag'] = 'td.testdb.test_table'
      puts h.to_json
    end
  rescue LoadError => e
    f.puts e.to_s
  end
}
```