[英]How to log outputs and errors to file without knowing where errors will occur
我有一個在遠程服務器上運行的長腳本,我想將所有輸出以及錯誤消息記錄到文件中。
# in script:
import sys sys.stdout = open('./myfile.txt', 'w')
# ...
sys.stdout.close()
# in terminal:
python myscript.py > ./myfile.txt
這會將所有 print() 輸出寫入我想要的文件。 但它不會將錯誤消息寫入文件以防萬一失敗。
import logging
try:
# ...
except ZeroDivisionError as e:
logging.error(e) # ERROR:root:division by zero
鏈接到日志記錄模塊的所有解決方案的問題是,我需要知道錯誤將在哪里發生以將其包裝在 logging.error() function 中。 但我並不總是知道我的錯誤會發生在哪里。
=>我如何(1)寫入所有輸出和(2)使我的腳本失敗的錯誤文件?
您必須將 python 錯誤 output sys.stderr
重定向到文件:
import sys
sys.stderr = open("errors.txt", "w")
我認為可以創建一個包含您要寫入的所有日志的新文件。 配置看起來像這樣:
import logging
logging.basicConfig(filename='std.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
這將 output 記錄消息到 std.log 文件
自己找到了答案:只需在終端中輸入,並確保您在正確的目錄中有一個 log.text 文件。 無需更改腳本。
python script.py &> ./log.txt
靈感來自這個問題: Redirect stdout and stderr to same file using Python
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.