I have Python script to send JSON logs to Logstash via TCP
- User
I have Python script to send JSON logs to Logstash via TCP
- Assistant
I have Python script to send JSON logs to Logstash via TCP
To send JSON logs from a Python script to Logstash over TCP, you need to ensure that Logstash is configured to accept inputs over TCP and that your Python script is correctly set up to send the logs. Below, I'll guide you through a basic example of how to accomplish this.
First, you need to configure Logstash to listen for TCP inputs. You can do this by creating a configuration file, e.g., logstash.conf, with the following content:
input {
tcp {
port => 5000
codec => json
}
}
output {
stdout {
codec => rubydebug
}
# Alternatively, you can send to Elasticsearch or any other output
# elasticsearch {
# hosts => ["http://localhost:9200"]
# index => "your_index"
# }
}
Here's a simple Python script that sends JSON logs to Logstash via a TCP connection:
import socket
import json
import time
def send_log(host, port, log_data):
"""
Send log data to Logstash via TCP.
:param host: Logstash host
:param port: Logstash TCP port
:param log_data: Dictionary containing log data
"""
try:
# Convert log data to JSON
json_log = json.dumps(log_data)
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the Logstash server
server_address = (host, port)
print(f'Connecting to {server_address}')
sock.connect(server_address)
try:
# Send data
print(f'Sending log data: {json_log}')
sock.sendall(json_log.encode('utf-8') + b'\n')
finally:
# Clean up the connection
print('Closing connection')
sock.close()
except Exception as e:
print(f'Error sending log: {e}')
if __name__ == '__main__':
log_data = {
"timestamp": time.strftime('%Y-%m-%d %H:%M:%S'),
"level": "INFO",
"message": "This is a sample log message"
}
logstash_host = 'localhost'
logstash_port = 5000
send_log(logstash_host, logstash_port, log_data)
Logstash Configuration:
tcp input module listens on port 5000 for incoming log data. It uses the json codec to parse incoming JSON logs.Python Script:
Make sure that any necessary network configurations (such as firewall rules) are in place to allow TCP traffic on the desired port. Adjust the Logstash host and port as necessary to fit your environment.