Hoja de Referencia de Fluentd¶
Instalación¶
| Platform | Comando |
|---|---|
| Ubuntu/Debian (td-agent) | curl -fsSL https://toolbelt.treasuredata.com/sh/install-ubuntu-jammy-td-agent4.sh \ | sh |
| RHEL/CentOS | curl -L https://toolbelt.treasuredata.com/sh/install-redhat-td-agent4.sh \ | sh |
| macOS | brew install fluentd |
| Ruby Gem | gem install fluentd |
| Docker | docker pull fluent/fluentd:latest |
| Kubernetes | Desplegar como DaemonSet (ver sección de Configuración) |
| Comando | Descripción |
|---|---|
fluentd -c fluent.conf |
Iniciar Fluentd con archivo de configuración especificado |
fluentd -c fluent.conf -vv |
Ejecutar con salida de depuración detallada |
fluentd -c fluent.conf --dry-run |
Validar configuración sin iniciar |
fluentd --setup ./fluent |
Crear estructura de directorio de configuración predeterminada |
fluentd --version |
Mostrar información de la versión de Fluentd |
sudo systemctl start td-agent |
Iniciar servicio td-agent (Linux) |
sudo systemctl stop td-agent |
Detener servicio td-agent |
sudo systemctl restart td-agent |
Reiniciar servicio td-agent |
sudo systemctl status td-agent |
Verificar estado del servicio td-agent |
sudo systemctl reload td-agent |
Recargar configuración sin reiniciar |
sudo systemctl enable td-agent |
Habilitar td-agent para iniciar al arranque |
sudo journalctl -u td-agent -f |
Seguir los registros del servicio td-agent en tiempo real |
echo '{"msg":"test"}' \ | fluent-cat debug.test |
Enviar mensaje de registro de prueba a Fluentd |
curl -X POST -d 'json={"event":"test"}' http://localhost:8888/test.cycle |
Enviar registro de prueba HTTP |
td-agent-gem list \ | grep fluent-plugin |
Lista de plugins de Fluentd instalados |
| Comando | Descripción |
|---|---|
fluentd -c fluent.conf -d /var/run/fluentd.pid |
Ejecutar Fluentd en modo daemon con archivo PID |
fluentd -c fluent.conf -o /var/log/fluentd.log |
Ejecutar con salida a archivo de registro específico |
fluentd -c fluent.conf --workers 4 |
Ejecutar con múltiples procesos de trabajador |
fluentd -c fluent.conf -vvv |
Ejecutar con registro de nivel de traza para depuración |
fluentd --show-plugin-config=input:tail |
Mostrar opciones de configuración para plugin específico |
td-agent-gem install fluent-plugin-elasticsearch |
Instalar complemento de salida de Elasticsearch |
td-agent-gem install fluent-plugin-kafka -v 0.17.5 |
Instalar versión específica del plugin de Kafka |
td-agent-gem update fluent-plugin-s3 |
Actualizar el plugin de S3 a la última versión |
td-agent-gem uninstall fluent-plugin-mongo |
Eliminar plugin de MongoDB |
td-agent-gem search -r fluent-plugin |
Buscar plugins disponibles en el repositorio |
fluent-cat --host 192.168.1.100 --port 24224 app.logs |
Enviar logs a instancia remota de Fluentd |
fluent-cat app.logs < /path/to/logfile.json |
Enviar contenido del archivo de registro a Fluentd |
docker run -d -p 24224:24224 -v /data/fluentd:/fluentd/etc fluent/fluentd |
Ejecutar Fluentd en Docker con configuración montada |
sudo kill -USR1 $(cat /var/run/td-agent/td-agent.pid) |
Recargar Fluentd de manera elegante (reabrir archivos de registro) |
sudo kill -USR2 $(cat /var/run/td-agent/td-agent.pid) |
Volver a abrir archivos de registro de Fluentd sin reiniciar |
Ubicaciones de Archivos de Configuración Principal¶
- td-agent (Linux):
/etc/td-agent/td-agent.conf - Instalación de Gem:
./fluent/fluent.conf - Docker:
/fluentd/etc/fluent.conf
Estructura de Configuración Básica¶
# Source: Input plugins
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
# Filter: Process/transform logs
<filter app.**>
@type record_transformer
<record>
hostname "#{Socket.gethostname}"
tag ${tag}
</record>
</filter>
# Match: Output plugins
<match app.**>
@type elasticsearch
host elasticsearch.local
port 9200
index_name fluentd
type_name fluentd
</match>
Plugins de Origen (Entrada)¶
# Forward input (receive from other Fluentd instances)
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
# Tail log files
<source>
@type tail
path /var/log/nginx/access.log
pos_file /var/log/td-agent/nginx-access.pos
tag nginx.access
<parse>
@type nginx
</parse>
</source>
# HTTP input
<source>
@type http
port 8888
bind 0.0.0.0
body_size_limit 32m
keepalive_timeout 10s
</source>
# Syslog input
<source>
@type syslog
port 5140
bind 0.0.0.0
tag system.syslog
</source>
Plugins de Filtro (Procesamiento)¶
# Add/modify record fields
<filter app.**>
@type record_transformer
<record>
hostname "#{Socket.gethostname}"
environment production
timestamp ${time}
</record>
</filter>
# Parse unstructured logs
<filter app.logs>
@type parser
key_name message
<parse>
@type json
</parse>
</filter>
# Grep filter (include/exclude)
<filter app.**>
@type grep
<regexp>
key level
pattern /^(ERROR|FATAL)$/
</regexp>
</filter>
# Modify tag
<match app.raw.**>
@type rewrite_tag_filter
<rule>
key level
pattern /^ERROR$/
tag app.error.${tag}
</rule>
</match>
Plugins de Coincidencia (Salida)¶
# Elasticsearch output
<match app.**>
@type elasticsearch
host elasticsearch.local
port 9200
logstash_format true
logstash_prefix fluentd
<buffer>
@type file
path /var/log/fluentd/buffer/elasticsearch
flush_interval 10s
retry_max_interval 300s
</buffer>
</match>
# S3 output
<match logs.**>
@type s3
aws_key_id YOUR_AWS_KEY_ID
aws_sec_key YOUR_AWS_SECRET_KEY
s3_bucket your-bucket-name
s3_region us-east-1
path logs/
time_slice_format %Y%m%d%H
<buffer time>
timekey 3600
timekey_wait 10m
</buffer>
</match>
# File output
<match debug.**>
@type file
path /var/log/fluentd/output
<buffer>
timekey 1d
timekey_use_utc true
</buffer>
</match>
# Forward to another Fluentd
<match forward.**>
@type forward
<server>
host 192.168.1.100
port 24224
</server>
<buffer>
@type file
path /var/log/fluentd/buffer/forward
</buffer>
</match>
# Stdout (debugging)
<match debug.**>
@type stdout
</match>
Configuración de Búfer¶
<match pattern.**>
@type elasticsearch
# File buffer with advanced settings
<buffer>
@type file
path /var/log/fluentd/buffer
# Flush settings
flush_mode interval
flush_interval 10s
flush_at_shutdown true
# Retry settings
retry_type exponential_backoff
retry_wait 10s
retry_max_interval 300s
retry_timeout 72h
retry_max_times 17
# Chunk settings
chunk_limit_size 5M
queue_limit_length 32
overflow_action drop_oldest_chunk
# Compression
compress gzip
</buffer>
</match>
# Memory buffer for high-performance
<match fast.**>
@type forward
<buffer>
@type memory
flush_interval 5s
chunk_limit_size 1M
queue_limit_length 64
</buffer>
</match>
Configuración Multi-Trabajador¶
<system>
workers 4
root_dir /var/log/fluentd
</system>
# Worker-specific sources
<worker 0>
<source>
@type forward
port 24224
</source>
</worker>
<worker 1-3>
<source>
@type tail
path /var/log/app/*.log
tag app.logs
</source>
</worker>
Enrutamiento Basado en Etiquetas¶
# Route to different pipelines using labels
<source>
@type forward
@label @mainstream
</source>
<source>
@type tail
path /var/log/secure.log
@label @security
</source>
<label @mainstream>
<filter **>
@type record_transformer
<record>
pipeline mainstream
</record>
</filter>
<match **>
@type elasticsearch
host es-main
</match>
</label>
<label @security>
<filter **>
@type grep
<regexp>
key message
pattern /authentication failure/
</regexp>
</filter>
<match **>
@type s3
s3_bucket security-logs
</match>
</label>
Casos de Uso Comunes¶
Caso de Uso 1: Recolectar Logs de Nginx a Elasticsearch¶
# Install Elasticsearch plugin
sudo td-agent-gem install fluent-plugin-elasticsearch
# Configure Fluentd
sudo tee /etc/td-agent/td-agent.conf > /dev/null <<'EOF'
<source>
@type tail
path /var/log/nginx/access.log
pos_file /var/log/td-agent/nginx-access.pos
tag nginx.access
<parse>
@type nginx
</parse>
</source>
<match nginx.access>
@type elasticsearch
host localhost
port 9200
logstash_format true
logstash_prefix nginx
<buffer>
flush_interval 10s
</buffer>
</match>
EOF
# Restart td-agent
sudo systemctl restart td-agent
# Verify logs are flowing
sudo journalctl -u td-agent -f
Caso de Uso 2: Recolección de Logs de Kubernetes¶
# Deploy Fluentd DaemonSet
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: fluentd
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: fluentd
rules:
- apiGroups: [""]
resources: ["pods", "namespaces"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: fluentd
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: fluentd
subjects:
- kind: ServiceAccount
name: fluentd
namespace: kube-system
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: fluentd
namespace: kube-system
spec:
selector:
matchLabels:
k8s-app: fluentd-logging
template:
metadata:
labels:
k8s-app: fluentd-logging
spec:
serviceAccountName: fluentd
containers:
- name: fluentd
image: fluent/fluentd-kubernetes-daemonset:v1-debian-elasticsearch
env:
- name: FLUENT_ELASTICSEARCH_HOST
value: "elasticsearch.logging.svc.cluster.local"
- name: FLUENT_ELASTICSEARCH_PORT
value: "9200"
volumeMounts:
- name: varlog
mountPath: /var/log
- name: varlibdockercontainers
mountPath: /var/lib/docker/containers
readOnly: true
volumes:
- name: varlog
hostPath:
path: /var/log
- name: varlibdockercontainers
hostPath:
path: /var/lib/docker/containers
EOF
# Check DaemonSet status
kubectl get daemonset -n kube-system fluentd
kubectl logs -n kube-system -l k8s-app=fluentd-logging --tail=50
Caso de Uso 3: Reenviar Logs a S3 con Rotación¶
# Install S3 plugin
sudo td-agent-gem install fluent-plugin-s3
# Configure S3 output
sudo tee /etc/td-agent/td-agent.conf > /dev/null <<'EOF'
<source>
@type tail
path /var/log/app/*.log
pos_file /var/log/td-agent/app.pos
tag app.logs
<parse>
@type json
</parse>
</source>
<match app.logs>
@type s3
aws_key_id YOUR_AWS_ACCESS_KEY
aws_sec_key YOUR_AWS_SECRET_KEY
s3_bucket my-application-logs
s3_region us-east-1
path logs/%Y/%m/%d/
s3_object_key_format %{path}%{time_slice}_%{index}.%{file_extension}
<buffer time>
@type file
path /var/log/td-agent/s3
timekey 3600
timekey_wait 10m
chunk_limit_size 256m
</buffer>
<format>
@type json
</format>
</match>
EOF
# Restart and verify
sudo systemctl restart td-agent
sudo systemctl status td-agent
Caso de Uso 4: Enrutamiento de Logs a Múltiples Destinos¶
# Configure routing to multiple destinations
sudo tee /etc/td-agent/td-agent.conf > /dev/null <<'EOF'
<source>
@type tail
path /var/log/app/application.log
pos_file /var/log/td-agent/app.pos
tag app.logs
<parse>
@type json
</parse>
</source>
# Copy logs to multiple destinations
<match app.logs>
@type copy
# Send to Elasticsearch
<store>
@type elasticsearch
host elasticsearch.local
port 9200
logstash_format true
</store>
# Send to S3 for archival
<store>
@type s3
s3_bucket app-logs-archive
path logs/
<buffer time>
timekey 86400
</buffer>
</store>
# Send errors to Slack
<store>
@type grep
<regexp>
key level
pattern /^ERROR$/
</regexp>
@type slack
webhook_url https://hooks.slack.com/services/YOUR/WEBHOOK/URL
channel alerts
username fluentd
</store>
</match>
EOF
sudo systemctl restart td-agent
Caso de Uso 5: Integración de Monitoreo de Rendimiento de Aplicaciones¶
# Configure APM log forwarding
sudo tee /etc/td-agent/td-agent.conf > /dev/null <<'EOF'
<source>
@type tail
path /var/log/app/*.log
pos_file /var/log/td-agent/app.pos
tag app.logs
<parse>
@type json
time_key timestamp
time_format %Y-%m-%dT%H:%M:%S.%NZ
</parse>
</source>
# Enrich logs with metadata
<filter app.logs>
@type record_transformer
<record>
hostname "#{Socket.gethostname}"
environment ${ENV['ENVIRONMENT'] || 'production'}
service_name myapp
trace_id ${record['trace_id']}
</record>
</filter>
# Calculate response time metrics
<filter app.logs>
@type prometheus
<metric>
name http_request_duration_seconds
type histogram
desc HTTP request duration
key response_time
</metric>
</filter>
# Forward to APM system
<match app.logs>
@type http
endpoint http://apm-server:8200/intake/v2/events
<buffer>
flush_interval 5s
</buffer>
</match>
EOF
sudo systemctl restart td-agent
Mejores Prácticas¶
-
Usar búferes basados en archivos para producción: Los búferes en memoria son más rápidos, pero los búferes de archivo previenen la pérdida de datos durante reinicios o fallos. Siempre use búferes de archivo con configuraciones de reintento apropiadas para logs críticos.
-
Implementar rotación y retención de logs adecuadas: Configurar
Would you like me to continue with the remaining translations or provide more details for any specific section?pos_filepara entradas de tail y establecer valores apropiadostimekeyen búferes para prevenir problemas de espacio en disco. Usarrotate_ageyrotate_sizepara salidas de archivos.
-
Etiquetar logs jerárquicamente: Usar etiquetas de notación de puntos (p. ej.,
app.production.web) para permitir enrutamiento y filtrado flexible. Esto permite hacer coincidir patrones comoapp.**oapp.production.*. -
Monitorear el rendimiento de Fluentd: Rastrear longitud de cola de búfer, conteos de reintentos y tasas de emisión. Usar plugin de Prometheus o monitoreo integrado para detectar cuellos de botella antes de que causen pérdida de datos.
-
Proteger datos sensibles: Usar
@type secure_forwardpara transmisión de logs encriptados, filtrar campos sensibles conrecord_modifier, y restringir permisos de archivos en archivos de configuración que contengan credenciales. -
Probar cambios de configuración: Siempre usar
--dry-runpara validar la sintaxis de configuración antes de implementar. Probar la lógica de enrutamiento con volúmenes pequeños de logs antes de aplicar a producción. -
Usar modo multi-worker con criterio: Habilitar workers para operaciones intensivas de CPU (análisis, filtrado) pero tener en cuenta que algunos plugins no soportan modo multi-worker. Comenzar con 2-4 workers y monitorear uso de CPU.
-
Implementar degradación gradual: Configurar
overflow_actionen búferes para manejar contrapresión (usardrop_oldest_chunkoblocksegún los requisitos). Establecer valoresretry_timeoutrazonables para prevenir reintentos infinitos. -
Separar preocupaciones con etiquetas: Usar directivas
@labelpara crear tuberías de procesamiento aisladas para diferentes tipos de logs. Esto mejora la mantenibilidad y previene enrutamiento no intencional. -
Mantener plugins actualizados: Actualizar regularmente Fluentd y plugins para obtener correcciones de seguridad y mejoras de rendimiento. Fijar versiones de plugins en producción para asegurar consistencia.
Resolución de problemas¶
| Problema | Solución |
|---|---|
| Fluentd won't start | Check syntax: fluentd -c fluent.conf --dry-run. Review logs: sudo journalctl -u td-agent -n 100. Verify file permissions on config and buffer directories. |
| Logs not being collected | Verify pos_file exists and is writable. Check file path patterns match actual log locations. Ensure log files have read permissions. Test with tail -f on the log file. |
| High memory usage | Switch from memory buffers to file buffers. Reduce chunk_limit_size and queue_limit_length. Enable multi-worker mode to distribute load. Check for memory leaks in custom plugins. |
| Buffer queue growing | Increase flush_interval or reduce log volume. Check downstream system capacity (Elasticsearch, S3). Verify network connectivity. Review retry_max_interval settings. |
| Logs being dropped | Check buffer overflow_action setting. Increase queue_limit_length and chunk_limit_size. Monitor disk space for file buffers. Review retry_timeout configuration. |
| Plugin installation fails | Ensure Ruby development headers installed: sudo apt-get install ruby-dev build-essential. Use correct gem command: td-agent-gem not gem. Check plugin compatibility with Fluentd version. |
| Parse errors in logs | Validate parser configuration with sample logs. Use @type regexp with proper regex patterns. Add error handling: emit_invalid_record_to_error true. Check time format strings. |
| Cannot connect to Elasticsearch | Verify Elasticsearch is running: curl http://elasticsearch:9200. Check firewall rules. Validate credentials if using authentication. Review Elasticsearch logs for rejection reasons. |
| Duplicate logs appearing | Check pos_file location is persistent across restarts. Verify only one Fluentd instance is running. Review read_from_head setting (should be false in production). |
| Slow log processing | Enable multi-worker mode. Optimize regex patterns in filters. Use @type grep before expensive parsers. Profile with --trace flag to identify bottlenecks. |
| SSL/TLS connection errors | Verify certificate paths and permissions. Check certificate expiration dates. Ensure CA bundle is up to date. Use verify_ssl false for testing only (not production). |