以下是自己寫的 記錄日志的代碼。(和logging不搭嘎,如果如要學loggging模塊,本文末尾有他人的鏈接。)
# prtlog.py ############################################# # -*- coding: utf-8 -*- """ Created on Wed Dec 12 10:46:06 2018 需求起源:1. 在spyder中寫python腳本時,經常要寫print來調試; 開發完執行時(python file.py),也需要運行log來找bug. 2. 如果用print, 運行時python file.py >> log 缺點:(1) file.py不結束無法查看log文件 (2)別人模塊中的輸出,會不斷在輸出到log. 3. 如果用logging模塊 缺點:(1) spyder調試時,log文件一直處於打開狀態 (2)在spyder中調試時不好用,logging好像主要為了記錄運行時的日志。 功能: 1. 開發時輸出print結果,運行時輸出同目錄下1.log文件 2. 保留最新log中前num行 3. 每次使用prtlog輸出都會打開並關閉1.log文件 缺點:效率不高(不追求效率就無所謂了) """ import os,sys import time,datetime def checklog(logfile,num=1000): #保留文件中至少num行 try: if os.path.exists(logfile): lines = open(logfile,'r').readlines() if len(lines)>num+num*0.5: #當文件大於num+500時,只保留最近num行,避免刪除重寫文件頻率太高。 os.remove(logfile) with open(logfile,'w') as f: for line in lines[-num:]: f.write(line) else: pass except: print('Wrong! : [fun]checklog.') def prtlog(logstr='123',linenum='',maxlines=1000): #linenum 指運行時所在行號 logstr= str(logstr);
dirname, filename = os.path.split(os.path.abspath(sys.argv[0])) logfile = os.path.join(dirname,'1.log') checklog(logfile,maxlines) with open(logfile,'a+') as f: lineheader='%s %s[%s]: '%(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),filename,linenum) f.write(lineheader+logstr+'\n') print(lineheader+logstr) f.close() if __name__ == '__main__': prtlog(logstr='123') # b.py ############################################# from prtlog import prtlog prtlog('haha',maxlines=10)
同目錄下生成1.log
運行prtlog.py3次,運行b.py3次. 1.log內容:
如需了解logging:
python中logging模塊的一些簡單用法 ★★★★★★★,
python模塊之logging ★★★★