Python Logstash

0.4.8 · active · verified Mon Apr 13

python-logstash is a Python logging handler for Logstash. It allows applications to send log messages to a Logstash instance using UDP, TCP, or AMQP protocols. The library is currently at version 0.4.8 and focuses on providing reliable, direct log forwarding, with updates addressing Python 3 compatibility and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure the Python logging module to send messages to Logstash using the default UDPLogstashHandler. It also shows how to include custom 'extra' fields in your log entries. Remember to set `version=1` for compatibility with modern Logstash versions and ensure your Logstash input is configured for UDP on the specified port.

import logging
import logstash
import sys
import os

# Configure Logstash host and port (use environment variables for production)
LOGSTASH_HOST = os.environ.get('LOGSTASH_HOST', 'localhost')
LOGSTASH_PORT = int(os.environ.get('LOGSTASH_PORT_UDP', 5959))

test_logger = logging.getLogger('my_logstash_app')
test_logger.setLevel(logging.INFO)

# Add Logstash UDP handler (default behavior)
test_logger.addHandler(logstash.LogstashHandler(LOGSTASH_HOST, LOGSTASH_PORT, version=1))

# Optional: Add Logstash TCP handler (uncomment and adjust port as needed)
# LOGSTASH_TCP_PORT = int(os.environ.get('LOGSTASH_PORT_TCP', 5000))
# test_logger.addHandler(logstash.TCPLogstashHandler(LOGSTASH_HOST, LOGSTASH_TCP_PORT, version=1))

# Log messages
test_logger.info('python-logstash: test logstash info message.')

# Add extra fields to logstash message
extra_data = {
    'test_string': 'python version: ' + repr(sys.version_info),
    'test_boolean': True,
    'test_dict': {'a': 1, 'b': 'c'},
    'test_float': 1.23,
    'test_integer': 123,
    'test_list': [1, 2, '3'],
}
test_logger.info('python-logstash: test extra fields', extra=extra_data)

try:
    1 / 0
except:
    test_logger.exception('python-logstash-app: Exception with stack trace!')

print(f"Logs sent to Logstash at {LOGSTASH_HOST}:{LOGSTASH_PORT} (UDP)")

view raw JSON →