Modify Fluentd Json Output
Modifying the JSON output in Fluentd allows you to customize the log format to suit your needs, such as adding, removing, or transforming fields before sending the logs to their destination. This is commonly done using the record_transformer filter, which can manipulate JSON logs based on your requirements.
Step-by-Step Guide to Modify Fluentd JSON Output
1. Basic Fluentd Configuration Example
Here’s a basic Fluentd configuration that demonstrates how to read JSON logs, transform them, and then output them to a file.
Example Input: Reading JSON Logs
Assuming you have logs coming from a tail input plugin:
2. Using record_transformer Filter to Modify JSON Logs
The record_transformer filter allows you to add, remove, or modify fields in the JSON log records.
Example Filter Configuration
Explanation
hostname: Adds a field with the current hostname.environment: Adds a static field with the valueproduction.user_id: Renames a field fromuser.idtouser_id.remove_field: Removes a field namedsensitive_datafrom the log.
3. Output Configuration
You can then specify how to output the modified logs. Here’s an example of sending the logs to a file in JSON format:
4. Advanced Transformation Using record_transformer
You can also use Ruby code within the record_transformer to perform more complex transformations.
Example: Advanced Transformation
Explanation
formatted_time: Uses Ruby to format the timestamp.full_message: Concatenates two fields into a new field.
5. Testing and Validation
After modifying your configuration:
Restart Fluentd to apply the changes:
Check the Output: Verify the transformed logs in the output file or destination to ensure that the modifications are applied as expected.
6. Common Use Cases
- Redacting Sensitive Information: Removing or masking sensitive data from logs.
- Adding Metadata: Adding contextual information like environment, application name, or hostname.
- Flattening Nested JSON: Transforming nested JSON into a flat structure for easier querying.
7. Using fluent-plugin-record-reformer
If you need more advanced record manipulation, consider using the fluent-plugin-record-reformer plugin, which provides additional capabilities for transforming records.