python寫入日誌檔案並實時輸出在控制台

2022-07-07 14:54:13 字數 1284 閱讀 4611

import logging

from logging import handlers

class logger(object):

level_relations = #日誌關係對映

def __init__(self,filename,level='info',backcount=10,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):

self.logger = logging.getlogger(filename)

format_str = logging.formatter(fmt) #設定日誌格式

self.logger.setlevel(self.level_relations.get(level))#設定日誌級別

sh = logging.streamhandler() #往螢幕上輸出

sh.setformatter(format_str) #設定螢幕上顯示的格式

self.logger.addhandler(sh) #把物件加到logger裡

fh = handlers.rotatingfilehandler(filename=filename,maxbytes=10485760,backupcount=backcount) # 按照檔案大小分割日誌檔案

fh.setlevel(self.level_relations.get(level))

fh.setformatter(format_str) #設定檔案裡寫入的格式

self.logger.addhandler(fh)

if __name__ == '__main__':

log = logger('my.log',level='debug')

log.logger.debug('------0. it is a debug ------')

log.logger.info('------ 1. it is a test ------')

log.logger.warning('------ 2. it is a warning ------')

log.logger.error('------ 3. it is an error ------')

log.logger.critical('------ 4. serious problem ------')

tail -f my.log

python 實時遍歷日誌檔案

open 遍歷乙個大日誌檔案 使用 readlines 還是 re 總體上 readlines 不慢於python 一次次呼叫 readline 因為前者的迴圈在c語言層面,而使用readline 的迴圈是在python語言層面。但是 readlines 會一次性把全部資料讀到記憶體中,記憶體佔用率...

Python日誌無延遲實時寫入的示例

我在用python生成日誌時,發現無論怎麼flush 檔案內容總是不能實時寫入,導致程式意外中斷時一無所獲。以下是查到的解決方案 親測可行 open 函式中有乙個bufferin的引數,預設是 1,如果設定為0是,就是無緩衝模式。但是用二進位制模式開啟這個檔案,並且把要寫入的資訊轉換byte lik...

Python 讀取檔案並分詞 檔案寫入

1 讀檔案 fr open file.txt for line in fr.readlines line line.strip listfromline line.split 簡單點寫 for line in open file.txt readlines listfromline line.str...