import socket
import time
import os
import threading
max_size = 10 * 1024 # 10 MB
timeInterval = 5
def write_error(msg):
filename = 'error.log'
if os.path.exists(filename) and os.path.getsize(filename) > max_size:
with open('error.log', 'w') as f:
f.write('')
with open(filename, 'a') as f:
f.write(msg)
def send_heartbeat(s):
try:
# 发送心跳
s.sendall('heartbeat'.encode())
print('Heartbeat sent')
threading.Timer(timeInterval, send_heartbeat, args=[s]).start()
except Exception as e:
print('Error:', e)
# 将异常信息写入文件
write_error(time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + str(e) + '\n')
threading.Timer(timeInterval, send_heartbeat, args=[s]).cancel()
# 每隔10秒发送一次心跳
def tcp_client():
while True:
try:
# 连接到指定的IP地址和端口号
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
print('Connected to server')
threading.Timer(timeInterval, send_heartbeat, args=[s]).start()
# 缓存数据
cache = []
while True:
# 接收数据
data = s.recv(1024)
if not data:
break
# 将数据按照时间戳添加到缓存中
cache.append(time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + data.decode())
print('Data received:', data.decode().strip())
# 如果缓存超过20行,则将缓存写入文件
if len(cache) >= 20:
filename = 'data_' + time.strftime('%Y-%m-%d_%H') + '.txt'
with open(filename, 'a') as f:
for line in cache:
f.write(line)
print('Data written to file:', filename)
cache = []
# 删除超过24小时的文件
for file in os.listdir('.'):
if file.startswith('data_') and file.endswith('.txt'):
file_time = time.mktime(time.strptime(file[5:-4], '%Y-%m-%d_%H'))
if time.time() - file_time > 24 * 60 * 60:
os.remove(file)
print('File deleted:', file)
except Exception as e:
print('Error:', e)
# 将异常信息写入文件
write_error(time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + str(e) + '\n')
# 等待5秒后重试
time.sleep(5)
if __name__ == '__main__':
tcp_client()
基于python的日志记录脚本
发布于 2023-04-24 554 次阅读

Comments | NOTHING