python 將終端 terminal 或者控制台的輸出結果輸出至 log 檔案 以檔案形式儲存
重定義 logger 類,然後 sys.stdout = logger(「log檔名及路徑」)
import sys
class
logger
(object):
def__init__
(self, logfile =
"default.log"):
self.terminal = sys.stdout
self.log =
open
(logfile,
'a')
defwrite
(self,message)
: self.terminal.write(message)
self.log.write(message)
defflush
(self)
:pass
sys.stdout = logger(
"log.log"
)
python 標準輸出 sys.stdout 重定向
使用 print obj 而非 print(obj)
一些背景
sys.stdout 與 print
當我們在 python 中列印物件呼叫 print obj 時候,事實上是呼叫了 sys.stdout.write(obj+』\n』)
print 將你需要的內容列印到了控制台,然後追加了乙個換行符
print 會呼叫 sys.stdout 的 write 方法
以下兩行在事實上等價:
sys.stdout.write(『hello』+』\n』)
print 『hello』
sys.stdin 與 raw_input
當我們用 raw_input('input promption: ') 時,事實上是先把提示資訊輸出,然後捕獲輸入
以下兩組在事實上等價:
hi=raw_input('hello? ')
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the 『\n』 in input stream
從控制台重定向到檔案
原始的 sys.stdout 指向控制台
如果把檔案的物件的引用賦給 sys.stdout,那麼 print 呼叫的就是檔案物件的 write 方法
f_handler=open(『out.log』, 『w』)
sys.stdout=f_handler
print 『hello』
記住,如果你還想在控制台列印一些東西的話,最好先將原始的控制台物件引用儲存下來,向檔案中列印之後再恢復 sys.stdout
複製**
console=sys.stdout
sys.stdout=console
複製**
同時重定向到控制台和檔案
如果我們希望列印的內容一方面輸出到控制台,另一方面輸出到檔案作為日誌儲存,那麼該怎麼辦?
將列印的內容保留在記憶體中,而不是一列印就將 buffer 釋放重新整理,那麼放到乙個字串區域中會怎樣?
a=』』
sys.stdout=a
print 『hello』
ok,上述**是無法正常執行的
traceback (most recent call last):
file 「.\hello.py」, line xx, in
print 『hello』
attributeerror: 『str』 object has no attribute 『write』
錯誤很明顯,就是上面強調過的,在嘗試呼叫 sys.stdout.write() 的時候,發現沒有 write 方法
另外,這裡之所以提示 attribute error 而不是找不到函式等等,我猜想是因為 python 將物件/類的函式指標記錄作為物件/類的乙個屬性來對待,只是保留了函式的入口位址
既然這樣,那麼我們必須給重定向到的物件實現乙個 write 方法:
複製**
import sys
classredirection:
def __init__(self):
self.buff=''
self.__console__=sys.stdout
def write(self, output_stream):
self.buff+=output_stream
def to_console(self):
sys.stdout=self.__console__
print self.buff
def to_file(self, file_path):
f=open(file_path,'w')
sys.stdout=f
print self.buff
f.close()
def flush(self):
self.buff=''
def reset(self):
sys.stdout=self.__console__
ifname==「main」:
# redirection
r_obj=redirection()
sys.stdout=r_obj
# get output stream
print 'hello'
print 'there'
# redirect to console
r_obj.to_console()
# redirect to file
r_obj.to_file('out.log')
# flush buffer
r_obj.flush()
# reset
r_obj.reset()
複製**
同樣的,sys.stderr, sys.stdin 也都可以被重定向到多個位址,舉一反三的事情就自己動手實踐吧
docker kafka日誌檔案重定向
專案採用docker compose啟動kafka,預設日誌檔案會寫入 var lib docker volumes 導致系統磁碟被寫滿。加入下面kafka log dirs配置,並且把配置的容器內位址對映到系統資料資料夾下即可 kafka image wurstmeister kafka cont...
Linux下日誌重定向
最近由於專案的需要,需要將ipc中的日誌同步到sd卡中,以便後續ipc出現問題了進行分析。由於我們程式的架構是多程序的,為了將所有程序的日誌同步到sd卡中,程序間需要傳遞檔案描述符,然後將該描述符重定向即可。include include include include include includ...
nohup 日誌重定向 日誌清空
在linux 系統上可以使用nohup 來執行命令,nohup 可以像控制台一樣完整顯示程式輸出的日誌資訊 簡單的用法 nohup test.sh test.log 2 1 這樣test.sh 執行所有的日誌資訊都會記錄在 test.log 中 在實際使用中 test.log 會隨著程式執行的時長和...