我目前有一个带有日志记录的TCP客户端代码,它将发送的数据保存在文本文件中。我希望发送的数据保存在一个文件夹中,该文件头是发送数据的时间戳。那可能吗?我尝试过使用多种方法,但我的代码仍然失败。有人可以给我一个指导,真的会帮助我,因为我已经坚持了很长一段时间。 这就是我的代码现在的样子:
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))
答案 0 :(得分:1)
您只需导入时间模块以生成时间戳并创建按时间戳命名的目录。
假设您希望按小时将日志文件剪切为不同的折叠。代码有点像吼叫:
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)
代码未经过测试。
答案 1 :(得分:0)
在以下位置查看Python日志记录模块:
http://docs.python.org/2/howto/logging.html#logging-basic-tutorial