跳到主要內容

[Python] 將運作過程的debug message紀錄到log file的功能

軟體在運作過程難免會遇到一些非預期的狀況讓程式掛點或是種種的不正常行為,這時候往往案發現場不能保留,很多的線索都在重新啟動軟體後消失了。若軟體的行為是要與其他軟體進行交互的,那就更難找出問題了。

所以把軟體運作過程中重要的階段記錄下來是很重要的事,一方面自己軟體的bug可以很快找到觸發的點,另一方面若是別人的軟體造成我們的軟體掛點,log也可以幫助我們提出證據來澄清,不讓別人冤枉我們。

1. 新增一個save log的function:
    def saveLog(self, data):
        currentDirectory = os.getcwd()
        print(currentDirectory)
        filePath = '%s\\Log.txt' % (currentDirectory)
        try:
            if os.path.exists(filePath):
                fileSize = os.path.getsize(filePath)
                print(fileSize)
                if fileSize > 50000000:#50MB
                    os.remove(filePath)
            else:
                print('Log file does not exists')
        except:
            print("Error while deleting Log file ", filePath)
            return

        try:
            file = open(filePath, 'a+')
            file.write('%s\n' % (data))
            file.close()
        except IOError:
            print('Delete Log error!!')
2. 在你要記錄log的地方加上如下的句子:
saveFstLog('%s : %s' % (time.strftime("%Y%m%d%H%M%S", time.localtime()),data))
如此就能將"現在時間"與字串"data"的內容寫入當前目錄下的Log.txt檔案,並且檔案大小如果超過50MB會自動重新記錄。

留言