您还未登录! 登录 | 注册 | 帮助  

您的位置: 首页 > 软件测试工具 > 性能测试工具 > 正文

用python做测试实现高性能测试工具(4)

发表于:2017-01-09 作者:网络转载 来源:

  在前面一篇中,不知道我文章中有神马关键字,图片总是上传不成功,为了大家看的方便,在这里上传
  多线程的系统架构:

  多线程改成多进程,只要把红线部分的线程改成多进程即可,但总的进程数最好不要超过CPU 核数。

  上面解决了系统的性能问题,但写log又引入了问题,多进程写log会引起混乱。
  查询了多进程写log 的方案, 主要有2种:
  利用多进程的Queue,把log放到统一的有个log queue里面,一个单独的线程写log
  起一个单独的socket server,由 这个server来接受log,并负责写log
  我觉得这2重方案都太重了,很多写log的地方就需要改动了,希望找到一个方案能直接不改动老代码写log的方式,开始考虑的是每个进程单独写一个log,但这样统计数据有点小不方便。 继续探索到,有个开源的项目(https://launchpad.net/python-concurrent-log-handler),已经实现了多进程写log,但目前只是实现了按文件大小RotatingFileHandler, 按时间rotate 的功能还没实现。不过这个已经足够用了。
try:
from cloghandler import ConcurrentRotatingFileHandler as RFHandler
except ImportError:
from warnings import warn
warn("ConcurrentLogHandler package not installed.  Using builtin log handler")
from logging.handlers import RotatingFileHandler as RFHandler
rotateHandler = RFHandler("sim.log", "a", 10*1024*1024, 5)
formatter = logging.Formatter('%(asctime)s [%(processName)s %(threadName)s %(levelname)s %(module)s:%(lineno)d] %(message)s')
rotateHandler.setFormatter(formatter)
log = logging.getLogger()
log.addHandler(rotateHandler)
log.setLevel(20)
rotateHandler = RFHandler("sim.log", "a", 10*1024*1024, 5)
  log文件名为sim.log,  文件到10M就会rotate, 最多保留5个文件
  formatter = logging.Formatter('%(asctime)s [%(processName)s %(threadName)s %(levelname)s %(module)s:%(lineno)d] %(message)s')   设置log输出的格式, 包括时间,进程名,线程名,模块名字,代码行数
  log.setLevel(20) 设置什么级别的log输出,   CRITICAL 50; ERROR 40; WARNING 30; INFO 20; DEBUG 10, NOSET 0;
import logging
import time
import multiprocessing
class Customer(multiprocessing.Process):
def __init__(self,mp_name):
multiprocessing.Process.__init__(self,name=mp_name)
def run(self):
while 1:
logging.debug(" I am here")
time.sleep(1)
for i in xrange(2):
mp=Customer("customer"+str(i))
mp.start()
  最后输出log的例子是:
2013-12-05 21:42:10,961 [customer0 MainThread DEBUG testqueue_old:115]  I am here
2013-12-05 21:42:15,361 [customer1 MainThread DEBUG testqueue_old:115]  I am here