1. 程式人生 > >python 執行日誌logging代替方案

python 執行日誌logging代替方案

 以下是自己寫的 記錄日誌的程式碼。(和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模組的一些簡單用法 ★★★★★★★,

python模組之logging ★★★★

Python之日誌處理(logging模組)★★★★