【问题标题】:Fastest way to write to a log in python在python中写入日志的最快方法
【发布时间】:2012-10-17 10:24:31
【问题描述】:

我在 uWSGI 中使用 gevent 循环并写入一个 redis 队列。我得到大约 3.5 qps。有时,redis 连接会出现问题,所以....如果失败,则写入一个文件,稍后我将有一个单独的进程进行清理。因为我的应用程序非常了解延迟,所以在 python 中转储到磁盘的最快方法是什么? python 日志记录就足够了吗?

【问题讨论】:

    标签: python logging uwsgi gevent


    【解决方案1】:

    如果延迟是您的应用程序的一个关键因素,那么无限期地写入磁盘可能会使事情变得非常糟糕。

    如果您想在 redis 仍处于关闭状态的情况下重新启动服务器,我认为除了写入磁盘之外没有其他解决方案,否则您可能想尝试使用 ramdisk。

    您确定拥有第二个服务器和第二个 redis 实例不是更好的选择吗?

    关于日志记录,我会简单地使用低级 I/O 函数,因为它们的开销较小(即使我们谈论的是很少的机器周期)

    【讨论】:

    • 在绝望中...打算诉诸伐木..是的..坏主意。我将 1) 创建一个专用的 redis 队列,2) 触发写入,而不是在 uWSGI 应用程序中,而是到另一个由 zmq 连接的进程。
    【解决方案2】:

    附加到磁盘上的文件很快。

    :~$ time echo "this happened" >> test.file
    
    real    0m0.000s
    user    0m0.000s
    sys     0m0.000s
    

    使用 Python 附加到文件似乎与 bash 的数量级大致相同。日志模块似乎确实增加了一点开销:

    import logging
    import time
    
    logging.basicConfig(filename='output_from_logging')
    counter = 0
    
    while counter < 3:
        start = time.time()
        with open('test_python_append', 'a') as f:
            f.write('something happened')
        counter += 1
        print 'file append took ', time.time() - start
    
    counter = 0
    while counter < 3:
        start = time.time()
        logging.warning('something happened')
        counter += 1
        print 'logging append took ', time.time() - start
    

    这给了我们这个输出:

    file append took  0.000263929367065
    file append took  6.79492950439e-05
    file append took  5.41210174561e-05
    logging append took  0.000214815139771
    logging append took  0.0001220703125
    logging append took  0.00010085105896
    

    但总体而言,我怀疑此操作将是您代码库中非常昂贵的部分,并且可能不值得担心。如果您担心延迟,那么您应该分析您的代码python -m cProfile code_to_test.py。这将告诉您每个函数需要多长时间以及您的应用程序在哪里花费时间。我严重怀疑它主要是记录错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      相关资源
      最近更新 更多