python logging模塊書寫日志以及日志分割詳解
更新時間:2019年07月22日 11:54:27 作者:raylu666
這篇文章主要為大家詳細介紹了python logging模塊書寫日志的方法,并對日志進行分割,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文范例是書寫兩個日志:錯誤日志(ERROR級別)和運行日志(DEBUG級別),其中運行日志每日凌晨進行分割
import logging,datetime,logging.handlers from conf import settings if __name__ == "__main__": #兩個日志,錯誤日志和運行日志,輸出文件路徑及文件名 error_log = settings.ERROR_LOG_FILE run_log = settings.RUN_LOG_FILE logger = logging.getLogger("mylog") logger.setLevel(logging.DEBUG) DATE_FORMAT = "%Y-%m-%d %H:%M:%S %p" LOG_FORMAT = "%(asctime)s------%(levelname)s[:%(lineno)d]-------%(message)s" #第一種普通寫法 #file_run_log = logging.FileHandler(run_log) #假如需要每日凌晨進行日志切割,注意導入模塊時需要導入logging.handlers,否則報錯 #when參數(shù)可以設置S M H D,分別是秒、分、小時、天分割,也可以按周幾分割,也可以凌晨分割 file_run_log = rf_handler = logging.handlers.TimedRotatingFileHandler(run_log, when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0)) file_error_log = logging.FileHandler(error_log) file_run_log.setLevel(level=logging.INFO) file_run_log.setFormatter(logging.Formatter(LOG_FORMAT)) file_error_log.setLevel(level=logging.ERROR) file_error_log.setFormatter(logging.Formatter(LOG_FORMAT)) logger.addHandler(file_run_log) logger.addHandler(file_error_log) logger.info("info test") logger.error("error test") logger.critical("critical test") #普通全局寫法 # logging.basicConfig(level=logging.DEBUG,filename=run_log,format=LOG_FORMAT,datefmt=DATE_FORMAT) # logging.info("this is a log") # logging.warning("this is warning")
settings.py:
ERROR_LOG_FILE = os.path.join(BASE_DIR,"log","error.log") RUN_LOG_FILE = os.path.join(BASE_DIR,"log","run.log")
日志輸出結果run.log:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python logging日志模塊 配置文件方式
- Python logging模塊異步線程寫日志實現(xiàn)過程解析
- Python日志處理模塊logging用法解析
- Python日志logging模塊功能與用法詳解
- python 日志 logging模塊詳細解析
- 解決Python logging模塊無法正常輸出日志的問題
- Python常用模塊logging——日志輸出功能(示例代碼)
- Python中使用logging和traceback模塊記錄日志和跟蹤異常
- python logging日志模塊以及多進程日志詳解
- python logging日志模塊的詳解
- python 日志模塊logging的使用場景及示例
相關文章
Python函數(shù)中參數(shù)是傳遞值還是引用詳解
這篇文章主要介紹了深入了解Python函數(shù)中參數(shù)是傳值還是傳引用,在 C/C++ 中,傳值和傳引用是函數(shù)參數(shù)傳遞的兩種方式,在Python中參數(shù)是如何傳遞的,需要的朋友可以參考下2019-07-07django框架使用orm實現(xiàn)批量更新數(shù)據(jù)的方法
這篇文章主要介紹了django框架使用orm實現(xiàn)批量更新數(shù)據(jù)的方法,結合實例形式簡單分析了Django基于orm操作數(shù)據(jù)庫更新數(shù)據(jù)的相關實現(xiàn)技巧,需要的朋友可以參考下2019-06-06Python的Bottle框架中返回靜態(tài)文件和JSON對象的方法
這篇文章主要介紹了Python的Bottle框架中返回靜態(tài)文件和JSON對象的方法,Bottle框架在Python開發(fā)者中具有很高的人氣,需要的朋友可以參考下2015-04-04Django1.7+python 2.78+pycharm配置mysql數(shù)據(jù)庫教程
原本感覺在Django1.7+python 2.78+pycharm環(huán)境下配置mysql數(shù)據(jù)庫是件很容易的事情,結果具體操作的時候才發(fā)現(xiàn),問題還是挺多的,這里記錄一下最終的配置結果,給需要的小伙伴參考下吧2014-11-11