2014-10-09 21 views
0

我想創建一個日誌文件,每次發生錯誤時都會向文本文件log.txt添加一行新行。我對python很陌生,所以也許我會錯過一些東西......但是每次發生錯誤時,log.txt都會被覆蓋,並且只顯示當前的錯誤消息,儘管錯誤信息每次都是不同的(由於時間戳),而我添加了\ n。使用時間戳+文件寫入消息

那是到目前爲止我的代碼:

 
import os 
import sys 
import time 
import datetime

try: path = sys.argv[1]

ts = time.time() sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ') #some more things but nothing else of interest for here except: error = "ERROR! No file 'bla' found!" log = 'log.txt' logfile = file(log, "w") logfile.write(sttime + error + '\n') logfile.close() sys.exit(0)

也許你能幫助我在這裏。我需要一個循環嗎?我嘗試創建一個空字符串(error =「」),它將錯誤消息添加到log.txt中,每次發生錯誤時都會加上+ =,但完全不起作用: - 。

+0

用''a「'作爲標誌打開文件,並將其追加。 – Aesthete 2014-10-09 10:27:11

回答

4

打開追加模式的文件作爲'w'模式將截斷該文件每次,即

logfile = open(log, "a") 

而且你應該使用with

with open(log, 'a') as logfile: 
    logfile.write(sttime + error + '\n') 

無需關閉文件,這會自動發生。

請注意,如果在path = sys.argv[1]處引發異常,則在嘗試登錄時可能未設置時間戳。在日誌代碼中獲取時間戳會更好。

此外,你不應該使用一個純粹的except子句,但至少要捕捉異常並報告它。

from datetime import datetime 

except Exception, exc: 
    sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ') 
    error = "ERROR! {}".format(exc) 
    log = 'log.txt' 
    with open(log, 'a') as logfile: 
     logfile.write(sttime + error + '\n') 
    raise 
# sys.exit(0) 
+0

謝謝!!!!就像那樣簡單。 – GeoEki 2014-10-09 10:49:11

+0

一旦你知道如何,這很容易。我已經解決了您的直接問題,但是,您應該考慮使用內置[日誌記錄模塊](https://docs.python.org/2/library/logging.html#module-logging) – mhawke 2014-10-09 10:53:54

+0

...並且您應該接受這個答案如果你發現它是正確的。 – mhawke 2014-10-09 10:54:58

1

當你做文件(日誌,'W')。文件日誌將變爲空。如果你想補充一點,你應該使用,而不是寬:

open(log, "a") 
-1
class Logger(object): 
    def __init__(self, n): 
     self.n = n 
     self.count = 0 
     self.log = open('log.txt', 'a') 


    def write(self, message): 
     self.count+=1 
     if self.count<self.n: 
      self.log.write("%s %s"% (time,message)) 
      self.log.flush() 
import sys 
sys.stdout= Logger() 

時間 - 是時間字符串格式化你想要的方式。

現在常規打印功能將寫入文件。

相關問題