Fluentd
1.0
1.0
  • Introduction
  • Overview
    • Life of a Fluentd event
    • Support
    • FAQ
    • Logo
    • fluent-package v5 vs td-agent v4
  • Installation
    • Before Installation
    • Install fluent-package
      • RPM Package (Red Hat Linux)
      • DEB Package (Debian/Ubuntu)
      • .dmg Package (macOS)
      • .msi Installer (Windows)
    • Install calyptia-fluentd
      • RPM Package (Red Hat Linux)
      • DEB Package (Debian/Ubuntu)
      • .dmg Package (macOS)
      • .msi Installer (Windows)
    • Install by Ruby Gem
    • Install from Source
    • Post Installation Guide
    • Obsolete Installation
      • Treasure Agent v4 (EOL) Installation
        • Install by RPM Package v4 (Red Hat Linux)
        • Install by DEB Package v4 (Debian/Ubuntu)
        • Install by .dmg Package v4 (macOS)
        • Install by .msi Installer v4 (Windows)
      • Treasure Agent v3 (EOL) Installation
        • Install by RPM Package v3 (Red Hat Linux)
        • Install by DEB Package v3 (Debian/Ubuntu)
        • Install by .dmg Package v3 (macOS)
        • Install by .msi Installer v3 (Windows)
  • Configuration
    • Config File Syntax
    • Config File Syntax (YAML)
    • Routing Examples
    • Config: Common Parameters
    • Config: Parse Section
    • Config: Buffer Section
    • Config: Format Section
    • Config: Extract Section
    • Config: Inject Section
    • Config: Transport Section
    • Config: Storage Section
    • Config: Service Discovery Section
  • Deployment
    • System Configuration
    • Logging
    • Signals
    • RPC
    • High Availability Config
    • Performance Tuning
    • Multi Process Workers
    • Failure Scenarios
    • Plugin Management
    • Trouble Shooting
    • Fluentd UI
    • Linux Capability
    • Command Line Option
    • Source Only Mode
    • Zero-downtime restart
  • Container Deployment
    • Docker Image
    • Docker Logging Driver
    • Docker Compose
    • Kubernetes
  • Monitoring Fluentd
    • Overview
    • Monitoring by Prometheus
    • Monitoring by REST API
  • Input Plugins
    • tail
    • forward
    • udp
    • tcp
    • unix
    • http
    • syslog
    • exec
    • sample
    • monitor_agent
    • windows_eventlog
  • Output Plugins
    • file
    • forward
    • http
    • exec
    • exec_filter
    • secondary_file
    • copy
    • relabel
    • roundrobin
    • stdout
    • null
    • s3
    • kafka
    • elasticsearch
    • opensearch
    • mongo
    • mongo_replset
    • rewrite_tag_filter
    • webhdfs
    • buffer
  • Filter Plugins
    • record_transformer
    • grep
    • parser
    • geoip
    • stdout
  • Parser Plugins
    • regexp
    • apache2
    • apache_error
    • nginx
    • syslog
    • ltsv
    • csv
    • tsv
    • json
    • msgpack
    • multiline
    • none
  • Formatter Plugins
    • out_file
    • json
    • ltsv
    • csv
    • msgpack
    • hash
    • single_value
    • stdout
    • tsv
  • Buffer Plugins
    • memory
    • file
    • file_single
  • Storage Plugins
    • local
  • Service Discovery Plugins
    • static
    • file
    • srv
  • Metrics Plugins
    • local
  • How-to Guides
    • Stream Analytics with Materialize
    • Send Apache Logs to S3
    • Send Apache Logs to Minio
    • Send Apache Logs to Mongodb
    • Send Syslog Data to Graylog
    • Send Syslog Data to InfluxDB
    • Send Syslog Data to Sematext
    • Data Analytics with Treasure Data
    • Data Collection with Hadoop (HDFS)
    • Simple Stream Processing with Fluentd
    • Stream Processing with Norikra
    • Stream Processing with Kinesis
    • Free Alternative To Splunk
    • Email Alerting like Splunk
    • How to Parse Syslog Messages
    • Cloud Data Logging with Raspberry Pi
  • Language Bindings
    • Java
    • Ruby
    • Python
    • Perl
    • PHP
    • Nodejs
    • Scala
  • Plugin Development
    • How to Write Input Plugin
    • How to Write Base Plugin
    • How to Write Buffer Plugin
    • How to Write Filter Plugin
    • How to Write Formatter Plugin
    • How to Write Output Plugin
    • How to Write Parser Plugin
    • How to Write Storage Plugin
    • How to Write Service Discovery Plugin
    • How to Write Tests for Plugin
    • Configuration Parameter Types
    • Upgrade Plugin from v0.12
  • Plugin Helper API
    • Plugin Helper: Child Process
    • Plugin Helper: Compat Parameters
    • Plugin Helper: Event Emitter
    • Plugin Helper: Event Loop
    • Plugin Helper: Extract
    • Plugin Helper: Formatter
    • Plugin Helper: Inject
    • Plugin Helper: Parser
    • Plugin Helper: Record Accessor
    • Plugin Helper: Server
    • Plugin Helper: Socket
    • Plugin Helper: Storage
    • Plugin Helper: Thread
    • Plugin Helper: Timer
    • Plugin Helper: Http Server
    • Plugin Helper: Service Discovery
  • Troubleshooting Guide
  • Appendix
    • Update from v0.12 to v1
    • td-agent v2 vs v3 vs v4
Powered by GitBook
On this page
  • How To Use Parsers From Plugins
  • Methods
  • Writing Tests
  • Overview of Tests

Was this helpful?

  1. Plugin Development

How to Write Parser Plugin

PreviousHow to Write Output PluginNextHow to Write Storage Plugin

Last updated 3 years ago

Was this helpful?

Fluentd supports . The plugin filenames prefixed parser_ are registered as Parser Plugins.

See for details on the common APIs for all the plugin types.

Here is an example of a custom parser that parses the following newline-delimited log format:

<timestamp><SPACE>key1=value1<DELIMITER>key2=value2<DELIMITER>key3=value...

like this:

2014-04-01T00:00:00 name=jake age=100 action=debugging

While it is not hard to write a regular expression to match this format, it is tricky to extract and save key names.

Here is the code to parse this custom format (let's call it time_key_value). It takes one optional parameter called delimiter, which is the delimiter for key/value pairs. It also takes time_format to parse the time string.

require 'fluent/plugin/parser'

module Fluent::Plugin
  class TimeKeyValueParser < Parser
    # Register this parser as 'time_key_value'
    Fluent::Plugin.register_parser('time_key_value', self)

    # `delimiter` is configurable with ' ' as default
    config_param :delimiter, :string, default: ' '

    # `time_format` is configurable
    config_param :time_format, :string, default: nil

    def configure(conf)
      super

      if @delimiter.length != 1
        raise ConfigError, "delimiter must be a single character. #{@delimiter} is not."
      end

      # `TimeParser` class is already available.
      # It takes a single argument as the time format
      # to parse the time string with.
      @time_parser = Fluent::TimeParser.new(@time_format)
    end

    def parse(text)
      time, key_values = text.split(' ', 2)
      time = @time_parser.parse(time)
      record = {}
      key_values.split(@delimiter).each do |kv|
        k, v = kv.split('=', 2)
        record[k] = v
      end
      yield time, record
    end
  end
end

Save this code as parser_time_key_value.rb in a loadable plugin path.

With in_tail configured as:

# Other lines...
<source>
  @type tail
  path /path/to/input/file
  <parse>
    @type time_key_value
  </parse>
</source>

this log line:

2014-01-01T00:00:00 k=v a=b

will be parsed as:

2014-01-01 00:00:00 +0000 test: {"k":"v","a":"b"}

How To Use Parsers From Plugins

Parser plugins are designed to be used with other plugins, like Input, Filter and Output. There is a Parser plugin helper solely for this purpose:

# in class definition
helpers :parser

# in #configure
@parser = parser_create(type: 'json')

# in input loop or #filter or ...
@parser.parse do |time, record|
  # ...
end

Methods

Parser plugins have a method to parse input (text) data to a structured record (Hash) with time.

#parse(text, &block)

It gets input data as text, and call &block to feed the results of the parser. The input text may contain two or more records so that means the parser plugin might call the &block two or more times for one argument.

Parser plugins must implement this method.

Writing Tests

Fluentd parser plugin has one or more points to be tested. Others (parsing configurations, controlling buffers, retries, flushes, etc.) are controlled by the Fluentd core.

Fluentd also provides the test driver for plugins. You can easily write tests for your own plugins:

# test/plugin/test_parser_your_own.rb

require 'test/unit'
require 'fluent/test/driver/parser'

# Your own plugin
require 'fluent/plugin/parser_your_own'

class ParserYourOwnTest < Test::Unit::TestCase
  def setup
    # Common setup
  end

  CONFIG = %[
    pattern apache
  ]

  def create_driver(conf = CONF)
    Fluent::Test::Driver::Parser.new(Fluent::Plugin::YourOwnParser).configure(conf)
  end

  sub_test_case 'configured with invalid configurations' do
    test 'empty' do
      assert_raise(Fluent::ConfigError) do
        create_driver('')
      end
    end
    # ...
  end

  sub_test_case 'plugin will parse text' do
    test 'record has a field' do
      d = create_driver(CONFIG)
      text = '192.168.0.1 - - [28/Feb/2013:12:00:00 +0900] "GET / HTTP/1.1" 200 777'
      expected_time = event_time('28/Feb/2013:12:00:00 +0900', format: '%d/%b/%Y:%H:%M:%S %z')
      expected_record = {
        'method' => 'GET',
        # ...
      }
      d.instance.parse(text) do |time, record|
        assert_equal(expected_time, time)
        assert_equal(expected_record, record)
      end
    end
  end
end

Overview of Tests

Testing for parser plugins is mainly for:

  • Validation of configuration (i.e. #configure)

  • Validation of the parsed time and record

To make testing easy, the plugin test driver provides a logger and the functionality to override the system and parser configurations, etc.

The lifecycle of plugin and test driver is:

  1. Instantiate plugin driver which then instantiates the plugin

  2. Configure plugin

  3. Run test code

  4. Assert results of tests by data provided by the driver

For:

  • configuration tests, repeat steps # 1-2

  • full feature tests, repeat steps # 1-4

For more details on <parse>, see .

See for details.

See for details.

If this article is incorrect or outdated, or omits critical information, please . is an open-source project under . All components are available under the Apache 2 License.

pluggable and customizable formats for input plugins
Plugin Base Class API
Parse Section Configurations
Parser Plugin Helper API
Testing API for Plugins
let us know
Fluentd
Cloud Native Computing Foundation (CNCF)