Send logs via TCP with Python
Using this script, you can send line-based logs as a TCP stream to logging application, e.g., NXLog.
In the following example, the goal is to send newline-delimited JSON events (NDJSON) in a file named events.ndjson to an NXLog agent listening on port 1514
events.ndjson
{"id":5122,"host":"i-34","msg":"Disk is full.","ts":"2023-08-02T22:46:43.307307+02:00"}
{"id":5123,"host":"i-07","msg":"Finished Rotate log files.","ts":"2023-08-02T22:46:44.812234+02:00"}
{"id":5124,"host":"dns1","msg":"all zones loaded","ts":"2023-08-02T22:46:48.2094698+02:00"}
Python script to stream line-based logs over TCP
import socket as s
filename = 'events.ndjson'
# Get local machine name
# host = s.gethostname()
host = '192.168.0.111'
port = 1514
# Create a socket object
tcp = s.socket(s.AF_INET, s.SOCK_STREAM)
# Establish socket connection
tcp.connect((host, port))
with open(filename) as file:
lines = [line.rstrip() for line in file]
lines = file.readlines()
for event in lines:
tcp.send(event.encode('utf-8'))
# Close socket connection
tcp.close()