Comprehensive guide for fluentd log routing covering essential concepts, practical examples, and production best practices.
Fluentd Log Routing is the process of defining how log events flow from sources, through transformations, and into destinations based on content, metadata, or structure. It matters when logs originate from diverse systems—microservices, databases, batch jobs, edge devices—with varying formats, volumes, and reliability requirements. A well-routed log system ensures that every log entry reaches the right consumer: structured logs go to analytics platforms, error logs trigger alerts, and high-cardinality logs are archived efficiently. Fluentd log routing is the glue between log generation and observability, and it’s most crucial during onboarding, incident response, and scaling.
Logs begin at sources, which Fluentd reads from files, sockets, HTTP, or message queues. The source configuration must specify how to parse incoming data and assign initial metadata.
A typical source block uses the in_tail plugin to read from files:
<source>
@type tail
path /var/log/app/*.log
pos_file /var/log/fluentd-app.pos
tag app.*
format none
read_from_head true
</source>
The path key defines glob patterns for input files. pos_file tracks the last read position using a file-based offset, enabling resumption after restarts. tag applies a structured name to every event, such as app.web, app.api, or app.worker.
When logs arrive in JSON format, the format json directive parses the body:
<source>
@type http
port 9880
bind 0.0.0.0
tag http.*
format json
</source>
This receives logs via HTTP POST to http://fluentd-host:9880. The payload must be valid JSON:
{
"message": "User login failed",
"user_id": 12345,
"level": "error",
"timestamp": "2025-04-05T10:30:00Z"
}
The tag is derived from the endpoint path—e.g., http.api.login—and format json parses the entire body into Fluentd’s event structure.
Routing rules are defined using <match> blocks. Each match applies to events whose tag matches a glob pattern, and it can transform and forward the event to one or more outputs.
To route errors to a dedicated Elasticsearch index:
<match app.*>
@type elasticsearch
host elasticsearch.example.com
port 9200
index_name app_logs
type_name _doc
log_es_400_error true
log_es_500_error true
flush_interval 5s
bulk_flush_interval 1s
</match>
This match applies to all tags starting with app., such as app.api, app.web, and app.worker. The @type elasticsearch directive sends events using the Elasticsearch HTTP API, with index_name and type_name configured.
The log_es_400_error and log_es_500_error flags enable logging of HTTP errors from Elasticsearch, which helps detect routing failures. If Elasticsearch returns a 400 error (e.g., malformed JSON), Fluentd logs the request and response body to its own log.
To route logs by field value, use the filter plugin:
<filter app.api.*>
@type parser
key_name message
format json
reserve_parser true
<parse>
@type json
time_key timestamp
time_format %FT%T%z
</parse>
</filter>
This parses the message field as JSON and extracts timestamp into Fluentd’s internal time field. The time_key is used for time-based batching and indexing.
The reserve_parser flag ensures that the parser is reused across events, avoiding repeated parsing overhead. When the message field is not valid JSON, Fluentd logs the error and stores the raw message as a fallback.
Filters modify event data in-flight. They can enrich, parse, extract, or mutate fields.
To enrich logs with metadata from an external service:
<filter app.*>
@type record_modifier
add_record {
"environment": "prod",
"region": "us-west-2"
}
remove_keys error, trace_id
append true
</filter>
The record_modifier plugin adds fixed fields (environment, region) and removes existing keys. append true means the new fields are merged into the existing record, not replacing it.
For more complex logic, use filter with record_transformer:
<filter app.*>
@type record_transformer
enable_ruby true
<record>
severity "#{record['level'].upcase}"
service "backend"
duration_ms "#{Time.now.to_f - record['timestamp'].to_f}"
</record>
</filter>
This evaluates Ruby code for each event. The record block defines key-value pairs where values are evaluated as Ruby expressions. record['level'] accesses the event’s level field, and Time.now.to_f returns the current time in seconds.
The enable_ruby flag allows full Ruby syntax, including conditionals, loops, and method calls.
When logs need to go to multiple destinations based on conditions, use multiple <match> blocks with overlapping tags.
To route high-severity logs to a monitoring system and all logs to a data warehouse:
<match app.*>
@type copy
<store>
@type elasticsearch
host elasticsearch.example.com
index_name app_logs
type_name _doc
</store>
<store>
@type kafka
brokers kafka1.example.com:9092,kafka2.example.com:9092
topic_name app_logs
acks 1
required_acks 1
sync false
</store>
</match>
The copy plugin duplicates each event to multiple outputs. The store blocks define individual outputs, each with their own configuration.
To route only error-level logs to a dedicated alerting system:
<match app.*>
@type filter
<filter>
@type record_modifier
add_record { "severity": "error" }
remove_keys "trace_id"
</filter>
<match>
@type elasticsearch
host alerting.example.com
index_name error_logs
type_name _doc
</match>
</match>
This applies a filter block that enriches the event, then matches all events that pass the filter to a second match. The match block can use tag patterns, field values, or even nested conditions.
Fluentd silently fails when the network to a destination is unavailable. The flush_interval and bulk_flush_interval options control batching and retries.
If a Kafka broker becomes unreachable, Fluentd logs:
2025-04-05 10:35:12 +0000 [warn]: Could not flush the buffer. retry_time=0
output="kafka"
error_class="Kafka::ConnectionError"
error="Connection refused - connect(2) for \"kafka1.example.com\" port 9092"
The retry_time indicates how long Fluentd waits before retrying the same buffer. The output field links the error to a specific output.
For message parsing failures, Fluentd logs:
2025-04-05 10:36:20 +0000 [error]: Parser failed to parse message
error_class="JSON::ParserError"
error="Expected value at line 1, column 1"
tag="app.api"
record="{\"message\": \"User login failed\", \"user_id\": 12345, \"level\": \"error\"}"
This error occurs when the message field is not valid JSON. The tag and record fields help trace the source of the failure.
The pos_file in in_tail is critical. If the file is rotated without Fluentd being restarted, the pos_file ensures no log is lost. But if the pos_file is not updated after a flush, log duplication occurs:
2025-04-05 10:40:00 +0000 [info]: Completed flush of 1234 records to elasticsearch.example.com
output="elasticsearch"
elapsed=1.234s
bytes=1.2MB
If Fluentd crashes after writing to the buffer but before updating the pos_file, subsequent restarts reprocess the same events.
To reduce memory usage, configure buffer and flush settings:
<match app.*>
@type elasticsearch
host elasticsearch.example.com
index_name app_logs
type_name _doc
<buffer>
@type file
path /var/log/fluentd/buffer/app
chunk_limit_size 1M
queue_limit_length 1000
flush_interval 3s
flush_at_shutdown true
overflow_action "discard_older_chunks"
</buffer>
</match>
The buffer section defines how Fluentd stores events before sending. @type file uses disk-based buffering. chunk_limit_size caps each chunk to 1MB. queue_limit_length limits the number of chunks in memory. flush_interval controls how often the buffer is flushed.
flush_at_shutdown ensures that all remaining events are sent when Fluentd stops. overflow_action defines behavior when the buffer queue is full: discard_older_chunks removes the oldest chunks to make room.
For high-throughput systems, sync and acks are critical. In Kafka, setting acks 1 means the producer waits for the leader to acknowledge the write. Setting sync false allows asynchronous delivery, reducing latency but increasing the chance of lost messages.
tag=app.api are routed to app.*, but a typo in the source (tag app.api. instead of app.api) causes the event to miss the match. Use tag app.* to catch all sub-tags.time_format is not set, Fluentd defaults to %Y-%m-%d %H:%M:%S, but a timestamp in ISO 8601 format (2025-04-05T10:30:00Z) is not parsed correctly.format json in in_tail parses the entire line, but if a log line contains multiple JSON objects (e.g., one per line), use format multiline with multiline_start_regexp to group lines.pos_file is shared across multiple Fluentd instances, concurrent writes can corrupt the position. Use file buffer with sync true to ensure atomic updates.log_es_400_error and log_es_500_error, a 400 error from Elasticsearch might go unnoticed. The error is logged only when log_es_error true is set.record_modifier applied before a parser may fail to parse fields that were added later.Fluentd log routing is not just configuration—it’s a contract between systems. A log event carries its journey through the system: from source to tag, through filters, and into outputs. When it fails, the logs tell the story.
This page was rewritten on 17 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy