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 DataFrame.groupby()聚合函數(shù),分組級運算
python的pandas包提供的數(shù)據(jù)聚合與分組運算功能很強大,也很靈活,本文就帶領大家一起來了解groupby技術,感興趣的朋友跟隨小編一起來看下2018-09-09
Python基礎之python循環(huán)控制語句break/continue詳解
Python中提供了兩個關鍵字用來控制循環(huán)語句,分別是break和continue,接下來通過兩個案例來區(qū)分這兩個控制語句的不同,感興趣的朋友一起看看吧2021-09-09
Python RuntimeWarning:invalid value encounter
這篇文章主要介紹了Python RuntimeWarning:invalid value encountered in double_scalars處理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Python?UnicodedecodeError編碼問題解決方法匯總
本文主要介紹了Python?UnicodedecodeError編碼問題解決方法匯總,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08

