client端代码
import logging
from logging.handlers import SysLogHandler
import time
# Create a logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Ensure the logger level is set to INFO
# Create a SysLogHandler
syslog_handler = SysLogHandler(address=('127.0.0.1', 5514)) # Adjust the address and port as needed
# Set the level of the handler to INFO
syslog_handler.setLevel(logging.INFO)
# Add the handler to the logger
logger.addHandler(syslog_handler)
# Define the data to send
data = {
"title": "test",
"Server_ip": "0.0.0.0",
"client": "test",
"client_ip": "1.1.1.1",
"class": "test",
}
# Convert the data to a string
data_str = str(data)
# Send the data to the syslog server
logger.info(data_str)
print(f"Sent log: {data_str}")
Server段代码
import socketserver
import threading
# Create a simple syslog server for testing
class SyslogUDPHandler(socketserver.BaseRequestHandler):
def handle(self):
data = bytes.decode(self.request[0].strip())
print(f"Received log: {data}")
def start_syslog_server(host='127.0.0.1', port=5514):
server = socketserver.UDPServer((host, port), SyslogUDPHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.daemon = True
server_thread.start()
return server
# Start the local syslog server
syslog_server = start_syslog_server()
print("Syslog server started.")
# Keep the main thread alive to allow continuous listening
try:
while True:
threading.Event().wait(1)
except KeyboardInterrupt:
print("Syslog server stopped.")
运行顺序
先启动服务端代码。
再启动客户端代码。