1#!/usr/bin/env python
2import sys
3from socket import *
4from time import strftime
5import datetime
6
7def main():
8  if len(sys.argv) < 4:
9    print "completion_logger_server.py <listen address> <listen port> <log file>"
10    exit(1)
11
12  host = sys.argv[1]
13  port = int(sys.argv[2])
14  buf = 1024 * 8
15  addr = (host,port)
16
17  # Create socket and bind to address
18  UDPSock = socket(AF_INET,SOCK_DGRAM)
19  UDPSock.bind(addr)
20
21  print "Listing on {0}:{1} and logging to '{2}'".format(host, port, sys.argv[3])
22
23  # Open the logging file.
24  f = open(sys.argv[3], "a")
25
26  # Receive messages
27  while 1:
28    data,addr = UDPSock.recvfrom(buf)
29    if not data:
30      break
31    else:
32      f.write("{ ");
33      f.write("\"time\": \"{0}\"".format(datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')))
34      f.write(", \"sender\": \"{0}\" ".format(addr[0]))
35      f.write(", \"data\": ")
36      f.write(data)
37      f.write(" }\n")
38      f.flush()
39
40  # Close socket
41  UDPSock.close()
42
43if __name__ == '__main__':
44  main()
45