Techioz Blog

Logstash コロンを矢印に置き換えます

概要

私の目標は、kinesis からデータを読み取り、CSV ファイルを s3 にアップロードすることですが、CSV ファイルでは、コロン (:) の代わりに矢印 (=>) が JSON データに入ってきます。

Logstash 構成ファイル

input {
  kinesis {
    application_name => "logstash"
    kinesis_stream_name => "events"
    type => "kinesis"
    region => "us-east-1"
    profile => "default"
    metrics => "cloudwatch"
    codec => "json"
  }
}

filter {
    grok {
      match => { "[data][ti]" => "%{YEAR:event_year}-%{MONTHNUM2:event_month}-%{MONTHDAY:event_day}" }
   }
}

output {
  s3 {
    bucket => "test-logstash"
    region => "us-east-1"
    prefix => "%{event_year}/%{event_month}/%{event_day}/%{[data][brandid]}/%{[data][event_name]}"
    encoding => "none"
    codec => csv {
        separator => "␁"
    }
    size_file => 200000000
    time_file => 60
  }
}

解決策

Logstash の mutate フィルターを使用して、「矢印 (=>)」を「コロン (:)」に置き換えることができます。

input {
  kinesis {
    application_name => "logstash"
    kinesis_stream_name => "events"
    type => "kinesis"
    region => "us-east-1"
    profile => "default"
    metrics => "cloudwatch"
    codec => "json"
  }
}

filter {
  # Use the mutate filter to replace "arrow (=>)" with "colon (:)"
  mutate {
    gsub => [
      "message", "=>", ":"
    ]
  }

  grok {
    match => { "[data][ti]" => "%{YEAR:event_year}-%{MONTHNUM2:event_month}-%{MONTHDAY:event_day}" }
  }
}

output {
  s3 {
    bucket => "test-logstash"
    region => "us-east-1"
    prefix => "%{event_year}/%{event_month}/%{event_day}/%{[data][brandid]}/%{[data][event_name]}"
    encoding => "none"
    codec => csv {
      separator => "␁"
    }
    size_file => 200000000
    time_file => 60
  }
}

フィルター セクションでは、mutate フィルターを使用してグローバル置換 (gsub) を実行し、「矢印 (=>)」を「コロン (:)」に置き換えます。これにより、JSON データが期待どおりに正しく処理されるようになります。

JSON データが別のフィールドにある場合は、変更フィルターのフィールド名 (メッセージ) を必ず調整してください。