Python Logging For Tcp Server
I am having some problems adding in a logging file for my python TCP server code. I've looked at some examples, but as I don't have much experience in writing my own scripts/codes,
Solution 1:
In context, maybe something like this?
#!/usr/local/cpython-2.7/bin/pythonimport socket
import thread
BUFF = 1024# buffer size
HOST = '127.0.0.1'
PORT = 1234# Port number for client & server to recieve datadefresponse(key):
return'Sent by client'deflogger(string, file_=open('logfile.txt', 'a'), lock=thread.allocate_lock()):
with lock:
file_.write(string)
file_.flush() # optional, makes data show up in the logfile more quickly, but is slowerdefhandler(clientsock, addr):
while1:
data = clientsock.recv(BUFF) # receive data(buffer).
logger('data:' + repr(data) + '\n') #Server to recieve data sent by client.ifnot data:
break#If connection is closed by client, server will break and stop recieving data.
logger('sent:' + repr(response('')) + '\n') # respond by saying "Sent By Client".if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while1:
logger('waiting for connection...\n')
clientsock, addr = serversock.accept()
logger('...connected from: ' + str(addr) + '\n') #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr))
HTH
Solution 2:
It sounds to me like your question would be better rephrased as “How do I read and write files within Python?”.
This is something well documented at: http://docs.python.org/2.7/tutorial/inputoutput.html#reading-and-writing-files
Example:
f = open('/tmp/log.txt', 'a')
f.write('Doing something')
do_something()
f.write('Other stuff')
other_stuff()
f.write('All finished')
f.close()
Post a Comment for "Python Logging For Tcp Server"