Python通过TCP向Logstash发送数据失败求助
Let's break down the possible issues step by step, based on the code and config you shared:
1. Incomplete Python Code (Most Likely Culprit)
Looking at your Python snippet, the connect call is cut off (sock.connect((HOST, PORT)...), and there's no code to actually send data to Logstash. Even if the connection succeeds, no data means nothing will show up in Logstash's output.
You need to:
- Complete the connection block
- Serialize your data to JSON
- Send the data with a trailing newline (Logstash's
jsoncodec expects one JSON object per line to parse correctly)
Here's a corrected, minimal working example:
import json import socket import sys HOST = "127.0.0.1" PORT = 5959 try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error as msg: sys.stderr.write(f"[ERROR] {msg}\n") sys.exit(1) try: sock.connect((HOST, PORT)) print("Successfully connected to Logstash") # Sample data to send data = {"event": "test_event", "message": "Hello from Python"} # Serialize to JSON and add newline json_data = json.dumps(data) + "\n" # Send the data sock.sendall(json_data.encode('utf-8')) print("Data sent successfully") except socket.error as msg: sys.stderr.write(f"[ERROR] Connection/Send failed: {msg}\n") sys.exit(1) finally: sock.close()
2. Verify Logstash is Running and Listening on Port 5959
Even if your code is fixed, if Logstash isn't running or isn't listening on the correct port, no data will transfer.
- Check if Logstash is running: Use your system's process manager (e.g.,
ps aux | grep logstashon Linux/macOS) - Verify the port is open: Run
ss -tulnp | grep 5959(Linux) ornetstat -an | findstr 5959(Windows) to confirm Logstash is bound to127.0.0.1:5959
3. Ensure Data Format Matches Logstash's Expectations
Logstash's json codec requires:
- Valid JSON syntax (no trailing commas, correct quotes, etc.)
- One JSON object per line. If you send multiple objects without newlines, Logstash won't parse them correctly.
4. Check Logstash Logs for Errors
If you still don't see data, check Logstash's log files (usually in /var/log/logstash/ on Linux, or in the Logstash installation directory's logs folder) for any connection errors or parsing issues.
内容的提问来源于stack exchange,提问作者Raj Rajeshwar Singh Rathore

