Fluent Logger for Python

0.11.1 · active · verified Fri Apr 10

fluent-logger-python is a Python library used to record events from Python applications to Fluentd or Fluent Bit. It provides both an event-based interface (`FluentSender`) and a standard Python `logging.Handler` (`FluentHandler`) for structured logging. The current version is 0.11.1 and it is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the standard Python `logging` module to send structured logs to Fluentd using `FluentHandler` and `FluentRecordFormatter`. It includes capturing extra contextual data and exception tracebacks.

import logging
from fluent import handler
import os

# Configure Fluentd to listen on 0.0.0.0:24224 (default)
# For a quick test, you can run Fluentd with:
# <source>
#   @type forward
#   port 24224
#   bind 0.0.0.0
# </source>
# <match app.**>
#   @type stdout
# </match>

# Set up a Python logger
logger = logging.getLogger('my_app')
logger.setLevel(logging.INFO)

# Configure FluentHandler
fluent_host = os.environ.get('FLUENTD_HOST', 'localhost')
fluent_port = int(os.environ.get('FLUENTD_PORT', 24224))

# The tag 'app.follow' will be used in Fluentd configuration to route logs
h = handler.FluentHandler('app.follow', host=fluent_host, port=fluent_port)

# Optional: Configure a formatter for structured logs
# The dictionary keys are the output field names in Fluentd
custom_format = {
    'host': '%(hostname)s',
    'where': '%(module)s.%(funcName)s',
    'type': '%(levelname)s',
    'message': '%(message)s',
    'stack_trace': '%(exc_text)s'
}
formatter = handler.FluentRecordFormatter(custom_format)
h.setFormatter(formatter)

# Add the FluentHandler to the logger
logger.addHandler(h)

try:
    logger.info('This is an info message from Python!', extra={'user_id': 123, 'action': 'login'})
    raise ValueError("Something went wrong here!")
except ValueError as e:
    logger.error('An error occurred.', exc_info=True, extra={'error_code': 500})

print(f"Logs sent to Fluentd at {fluent_host}:{fluent_port} with tag 'app.follow'")
print("Check your Fluentd/Fluent Bit output.")

view raw JSON →