簡體   English   中英

寫入python日志的最快方法

[英]Fastest way to write to a log in python

我在uWSGI中使用gevent循環,然后寫入redis隊列。 我得到大約3.5 qps。 有時候,redis連接會出現問題......如果失敗,那么寫一個文件,我將有一個單獨的進程稍后進行清理。 因為我的應用程序非常了解延遲,在python中轉儲到磁盤的最快方法是什么? python日志記錄是否足夠?

如果延遲是您的應用程序的關鍵因素,無限期寫入磁盤可能會使事情變得非常糟糕。

如果你希望在redis仍處於運行狀態時重啟你的服務器,我認為沒有其他解決方案而不是寫入磁盤,否則你可能想嘗試使用ramdisk。

你確定第二台帶有第二個redis實例的服務器不是更好的選擇嗎?

關於日志記錄,我只是使用低級I / O函數,因為它們的開銷較小(即使我們談論的機器周期很少)

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

:~$ 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 這將告訴您每個函數的使用時間以及應用程序花費時間的位置。 我嚴重懷疑它主要是記錄錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM