Python中l(wèi)ogging日志記錄到文件及自動分割的操作代碼
日志作為項目開發(fā)和運行中必備組件,python提供了內(nèi)置的logging模塊來完成這個工作;借助 TimedRotatingFileHandler 可以按日期自動分割日志,自動保留日志文件數(shù)量等,下面是對日志的一個簡單封裝和測試。
import loggingimport osfrom logging import handlersclass Logger(object): # 日志級別關(guān)系映射 level_relations = { ’debug’: logging.DEBUG, ’info’: logging.INFO, ’warning’: logging.WARNING, ’error’: logging.ERROR, ’critical’: logging.CRITICAL } def __init__(self, filename, level=’info’, when=’D’, back_count=3, fmt=’%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s’): f_dir, f_name = os.path.split(filename) os.makedirs(f_dir, exist_ok=True) # 當前目錄新建log文件夾 self.logger = logging.getLogger(filename) format_str = logging.Formatter(fmt) # 設(shè)置日志格式 self.logger.setLevel(self.level_relations.get(level)) # 設(shè)置日志級別 sh = logging.StreamHandler() # 往屏幕上輸出 sh.setFormatter(format_str) # 設(shè)置屏幕上顯示的格式 th = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=back_count, encoding=’utf-8’) # 往文件里寫入指定間隔時間自動生成文件的Handler # 實例化TimedRotatingFileHandler # interval是時間間隔,backupCount是備份文件的個數(shù),如果超過這個個數(shù),就會自動刪除,when是間隔的時間單位,單位有以下幾種: # S 秒 # M 分 # H 小時 # D 天 # ’W0’-’W6’ 每星期(interval=0時代表星期一:W0) # midnight 每天凌晨 th.setFormatter(format_str) # 設(shè)置文件里寫入的格式 self.logger.addHandler(sh) # 把對象加到logger里 self.logger.addHandler(th)# 測試if __name__ == ’__main__’: logger = Logger(’./logs/2020/app.log’, ’debug’, ’S’, 5).logger logger.debug(’debug’) logger.info(’info’) logger.warning(’警告’) logger.error(’報錯’) logger.critical(’嚴重’) # 單獨記錄error err_logger = Logger(’./logs/2020/error.log’, ’error’, ’S’, 3).logger err_logger.error(’錯誤 error’)
為了測試方便,我們將時間間隔設(shè)為秒(按秒自動命名分割文件),多運行幾次后,會按照配置文件數(shù)量將多余的日志文件自動刪除,保留如上圖中的日志文件。
原文鏈接:https://beltxman.com/3195.html,若無特殊說明本站內(nèi)容為行星帶原創(chuàng),未經(jīng)同意禁止轉(zhuǎn)載!
總結(jié)
到此這篇關(guān)于Python中l(wèi)ogging日志記錄到文件及自動分割的文章就介紹到這了,更多相關(guān)python logging日志記錄內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?2. 基于javaweb+jsp實現(xiàn)企業(yè)車輛管理系統(tǒng)3. 利用ajax+php實現(xiàn)商品價格計算4. ASP.Net MVC利用NPOI導入導出Excel的示例代碼5. jstl 字符串處理函數(shù)6. JSP動態(tài)網(wǎng)頁開發(fā)原理詳解7. PHP中為什么使用file_get_contents("php://input")接收微信通知8. XML CDATA是什么?9. IOS蘋果AppStore內(nèi)購付款的服務(wù)器端php驗證方法(使用thinkphp)10. .Net core Blazor+自定義日志提供器實現(xiàn)實時日志查看器的原理解析
