How to add logging to a file with timestamps to a Python TCP Server for Raspberry Pi

Viewed 20599

I am kinda stuck for my project & I desperately need help. I need a simple TCP server python code that has features like logging & time stamp which I could use for my Raspberry Pi. Its for my Final Year Project.

I've looked at some examples, but as I don't have much experience in writing my own scripts/codes, I'm not very sure how to go about doing this. I would appreciate if someone could guide me in the right direction with explanation and some examples if possible.

I am using HERCULES SETUP UTILITY , which acts as my TCP client, while my visual studio python code acts as a SERVER. My SERVER can receive the data which is sent by the client by now , I just can't seem to add in a logging file which can save the sent data into text file.Can someone please show me some examples or referance please? Your help would mean alot. This is my code so far :

from socket import *
import thread

BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
    return 'Sent by client'

def handler(clientsock,addr):
    while 1:
        data = clientsock.recv(BUFF) # receive data(buffer).
        print 'data:' + repr(data)   #Server to recieve data sent by client.
        if not data: break           #If connection is closed by client, server will        break and stop recieving data.
        print 'sent:' + repr(response('')) # respond by saying "Sent By Client". 



if __name__=='__main__':
    ADDR = (HOST, PORT) #Define Addr
    serversock = socket(AF_INET, SOCK_STREAM) 
    serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and     port number)
    serversock.listen(0)
    while 1:
        print 'waiting for connection...'
        clientsock, addr = serversock.accept()
        print '...connected from:', addr #show its connected to which addr
        thread.start_new_thread(handler, (clientsock, addr ))
1 Answers
Related