main主体
import time
import sys
from test.utils import TraceLog
class Server(object):
def printLog(self):
print("start server")
for i in range(10):
print(i)
time.sleep(0.1)
print("end server
")
if __name__ == '__main__':
traceLog = TraceLog("main.log")
traceLog.start()
sys.stdout = traceLog
sys.stderr = traceLog
server = Server()
server.printLog()
# 每当调用print的时候,底层就是在代用sys.stdout.write(str)
# sys.stdout.write() = traceLog.write()
utils工具
'''
不断记录服务端输入的日志
实现 >> 和 > 功能
'''
import codecs
from threading import Thread, Lock
import os
class TraceLog(Thread):
def __init__(self, logName):
# super().__init__() #python3的调用父类的方法,python2用的是super(Class, self).xxx,也是等价于Thread.__init__(self)
Thread.__init__(self)
self.logName = logName
self.lock = Lock()
self.contexts = []
def isFile(self):
if not os.path.exists(self.logName):
with codecs.open(self.logName, 'w') as f:
f.write("this log name is: {0} ".format(self.logName))
f.write("start log ")
def write(self, context):
self.contexts.append(context)
def run(self):
while 1:
# self.lock.acquire()
if len(self.contexts) != 0:
with codecs.open(self.logName, "a") as f:
for context in self.contexts:
f.write(context)
del self.contexts[:] # 注意不能忘记清空
# self.lock.release()