Reputation: 9
I currently have a TCP client code with logging which saves the sent data in a text file. I want the data sent to be saved in a folder which header is the time stamp of the sent data. Is that possible? I have tried using several methods but my code kept failing. Could someone give me a guide , would really be such a helping hand as I have been stuck on this for quite awhile. This is how my code looks like now:
import socket
import thread
import sys
BUFF = 1024 # buffer size
HOST = '172.16.166.206'
PORT = 1234 # Port number for client & server to receive data
def response(key):
return 'Sent by client'
def logger(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 slower
sys.stdout.write(string)
def handler(clientsock, addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
logger('data:' + repr(data) + '\n') #Server to receive data sent by client.
if not data:
break #If connection is closed by client, server will break and stop receiving 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(5)
while 1:
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))
Upvotes: 0
Views: 1727
Reputation: 7255
You just need to import time module to generate the time stamp and create the directory named by time stamp.
Suppose you want to cut the log file into different folds by hour. The code will somewhat like bellow:
import time
import os
def logger(string, file_name='logfile.txt', lock=thread.allocate_lock()):
with lock:
time_stamp = time.strftime("%Y%m%d%H",time.localtime())
if not os.path.isdir(time_stamp): os.mkdir(time_stamp)
with open(os.path.join(time_stamp, file_name), "a") as file_:
file_.write(string)
file_.flush()
sys.stdout.write(string)
The code is not tested.
Upvotes: 1
Reputation: 1911
Check out the Python logging module at:
http://docs.python.org/2/howto/logging.html#logging-basic-tutorial
Upvotes: 0