用python做自动化测试--实现高性能测试工具(5) --多进程写log

    在上一篇中解决了系统的性能问题,但写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





  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值