python logging模塊書寫日志以及日志分割詳解
本文范例是書寫兩個(gè)日志:錯(cuò)誤日志(ERROR級(jí)別)和運(yùn)行日志(DEBUG級(jí)別),其中運(yùn)行日志每日凌晨進(jìn)行分割
import logging,datetime,logging.handlers
from conf import settings
if __name__ == "__main__":
#兩個(gè)日志,錯(cuò)誤日志和運(yùn)行日志,輸出文件路徑及文件名
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)
#假如需要每日凌晨進(jìn)行日志切割,注意導(dǎo)入模塊時(shí)需要導(dǎo)入logging.handlers,否則報(bào)錯(cuò)
#when參數(shù)可以設(shè)置S M H D,分別是秒、分、小時(shí)、天分割,也可以按周幾分割,也可以凌晨分割
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")
日志輸出結(jié)果run.log:

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python爬蟲之自動(dòng)登錄與驗(yàn)證碼識(shí)別
這篇文章主要為大家詳細(xì)介紹了python爬蟲之自動(dòng)登錄與驗(yàn)證碼識(shí)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
Python DataFrame.groupby()聚合函數(shù),分組級(jí)運(yùn)算
python的pandas包提供的數(shù)據(jù)聚合與分組運(yùn)算功能很強(qiáng)大,也很靈活,本文就帶領(lǐng)大家一起來了解groupby技術(shù),感興趣的朋友跟隨小編一起來看下2018-09-09
python常用數(shù)據(jù)重復(fù)項(xiàng)處理方法
在本篇文章里小編給大家整理的是關(guān)于python常用數(shù)據(jù)重復(fù)項(xiàng)處理方法,需要的朋友們參考下。2019-11-11
Python基礎(chǔ)之python循環(huán)控制語句break/continue詳解
Python中提供了兩個(gè)關(guān)鍵字用來控制循環(huán)語句,分別是break和continue,接下來通過兩個(gè)案例來區(qū)分這兩個(gè)控制語句的不同,感興趣的朋友一起看看吧2021-09-09
Python RuntimeWarning:invalid value encounter
這篇文章主要介紹了Python RuntimeWarning:invalid value encountered in double_scalars處理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
Python?UnicodedecodeError編碼問題解決方法匯總
本文主要介紹了Python?UnicodedecodeError編碼問題解決方法匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08

