一文詳解Python中l(wèi)ogging模塊的用法
一、低配logging
日志總共分為以下五個級別,這個五個級別自下而上進(jìn)行匹配 debug-->info-->warning-->error-->critical,默認(rèn)最低級別為warning級別。
1.v1
import logging logging.debug('調(diào)試信息') logging.info('正常信息') logging.warning('警告信息') logging.error('報錯信息') logging.critical('嚴(yán)重錯誤信息')
WARNING:root:警告信息
ERROR:root:報錯信息
CRITICAL:root:嚴(yán)重錯誤信息
v1版本無法指定日志的級別;無法指定日志的格式;只能往屏幕打印,無法寫入文件。因此可以改成下述的代碼。
2.v2
import logging # 日志的基本配置 logging.basicConfig(filename='access.log', format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p', level=10) logging.debug('調(diào)試信息') # 10 logging.info('正常信息') # 20 logging.warning('警告信息') # 30 logging.error('報錯信息') # 40 logging.critical('嚴(yán)重錯誤信息') # 50
可在logging.basicConfig()函數(shù)中可通過具體參數(shù)來更改logging模塊默認(rèn)行為,可用參數(shù)有:
- filename:用指定的文件名創(chuàng)建FiledHandler(后邊會具體講解handler的概念),這樣日志會被存儲在指定的文件中。
- filemode:文件打開方式,在指定了filename時使用這個參數(shù),默認(rèn)值為“a”還可指定為“w”。
- format:指定handler使用的日志顯示格式。
- datefmt:指定日期時間格式。
- level:設(shè)置rootlogger(后邊會講解具體概念)的日志級別
- stream:用指定的stream創(chuàng)建StreamHandler??梢灾付ㄝ敵龅絪ys.stderr,sys.stdout或者文件,默認(rèn)為sys.stderr。若同時列出了filename和stream兩個參數(shù),則stream參數(shù)會被忽略。
format參數(shù)中可能用到的格式化串:
- %(name)s Logger的名字
- %(levelno)s 數(shù)字形式的日志級別
- %(levelname)s 文本形式的日志級別
- %(pathname)s 調(diào)用日志輸出函數(shù)的模塊的完整路徑名,可能沒有
- %(filename)s 調(diào)用日志輸出函數(shù)的模塊的文件名
- %(module)s 調(diào)用日志輸出函數(shù)的模塊名
- %(funcName)s 調(diào)用日志輸出函數(shù)的函數(shù)名
- %(lineno)d 調(diào)用日志輸出函數(shù)的語句所在的代碼行
- %(created)f 當(dāng)前時間,用UNIX標(biāo)準(zhǔn)的表示時間的浮 點(diǎn)數(shù)表示
- %(relativeCreated)d 輸出日志信息時的,自Logger創(chuàng)建以 來的毫秒數(shù)
- %(asctime)s 字符串形式的當(dāng)前時間。默認(rèn)格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒
- %(thread)d 線程ID。可能沒有
- %(threadName)s 線程名??赡軟]有
- %(process)d 進(jìn)程ID??赡軟]有
- %(message)s用戶輸出的消息
v2版本不能指定字符編碼;只能往文件中打印。
3.v3
logging模塊包含四種角色:logger、Filter、Formatter對象、Handler
- logger:產(chǎn)生日志的對象
- Filter:過濾日志的對象
- Formatter對象:可以定制不同的日志格式對象,然后綁定給不同的Handler對象使用,以此來控制不同的Handler的日志格式
- Handler:接收日志然后控制打印到不同的地方,F(xiàn)ileHandler用來打印到文件中,StreamHandler用來打印到終端
''' critical=50 error =40 warning =30 info = 20 debug =10 ''' import logging # 1、logger對象:負(fù)責(zé)產(chǎn)生日志,然后交給Filter過濾,然后交給不同的Handler輸出 logger = logging.getLogger(__file__) # 2、Filter對象:不常用,略 # 3、Handler對象:接收logger傳來的日志,然后控制輸出 h1 = logging.FileHandler('t1.log') # 打印到文件 h2 = logging.FileHandler('t2.log') # 打印到文件 sm = logging.StreamHandler() # 打印到終端 # 4、Formatter對象:日志格式 formmater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p',) formmater2 = logging.Formatter('%(asctime)s : %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p',) formmater3 = logging.Formatter('%(name)s %(message)s',) # 5、為Handler對象綁定格式 h1.setFormatter(formmater1) h2.setFormatter(formmater2) sm.setFormatter(formmater3) # 6、將Handler添加給logger并設(shè)置日志級別 logger.addHandler(h1) logger.addHandler(h2) logger.addHandler(sm) # 設(shè)置日志級別,可以在兩個關(guān)卡進(jìn)行設(shè)置logger與handler # logger是第一級過濾,然后才能到handler logger.setLevel(30) h1.setLevel(10) h2.setLevel(10) sm.setLevel(10) # 7、測試 logger.debug('debug') logger.info('info') logger.warning('warning') logger.error('error') logger.critical('critical')
二、高配logging
1.配置日志文件
以上三個版本的日志只是為了引出我們下面的日志配置文件
import os import logging.config # 定義三種日志輸出格式 開始 standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \ '[%(levelname)s][%(message)s]' # 其中name為getLogger()指定的名字;lineno為調(diào)用日志輸出函數(shù)的語句所在的代碼行 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # 定義日志輸出格式 結(jié)束 logfile_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # log文件的目錄,需要自定義文件路徑 # atm logfile_dir = os.path.join(logfile_dir, 'log') # C:\Users\oldboy\Desktop\atm\log logfile_name = 'log.log' # log文件名,需要自定義路徑名 # 如果不存在定義的日志目錄就創(chuàng)建一個 if not os.path.isdir(logfile_dir): # C:\Users\oldboy\Desktop\atm\log os.mkdir(logfile_dir) # log文件的全路徑 logfile_path = os.path.join(logfile_dir, logfile_name) # C:\Users\oldboy\Desktop\atm\log\log.log # 定義日志路徑 結(jié)束 # log配置字典 LOGGING_DIC = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': standard_format }, 'simple': { 'format': simple_format }, }, 'filters': {}, # filter可以不定義 'handlers': { # 打印到終端的日志 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', # 打印到屏幕 'formatter': 'simple' }, # 打印到文件的日志,收集info及以上的日志 'default': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件 'formatter': 'standard', 'filename': logfile_path, # 日志文件 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M (*****) 'backupCount': 5, 'encoding': 'utf-8', # 日志文件的編碼,再也不用擔(dān)心中文log亂碼了 }, }, 'loggers': { # logging.getLogger(__name__)拿到的logger配置。如果''設(shè)置為固定值logger1,則下次導(dǎo)入必須設(shè)置成logging.getLogger('logger1') '': { # 這里把上面定義的兩個handler都加上,即log數(shù)據(jù)既寫入文件又打印到屏幕 'handlers': ['default', 'console'], 'level': 'DEBUG', 'propagate': False, # 向上(更高level的logger)傳遞 }, }, } def load_my_logging_cfg(): logging.config.dictConfig(LOGGING_DIC) # 導(dǎo)入上面定義的logging配置 logger = logging.getLogger(__name__) # 生成一個log實(shí)例 logger.info('It works!') # 記錄該文件的運(yùn)行狀態(tài) return logger if __name__ == '__main__': load_my_logging_cfg()
2.使用日志
import time import logging import my_logging # 導(dǎo)入自定義的logging配置 logger = logging.getLogger(__name__) # 生成logger實(shí)例 def demo(): logger.debug("start range... time:{}".format(time.time())) logger.info("中文測試開始。。。") for i in range(10): logger.debug("i:{}".format(i)) time.sleep(0.2) else: logger.debug("over range... time:{}".format(time.time())) logger.info("中文測試結(jié)束。。。") if __name__ == "__main__": my_logging.load_my_logging_cfg() # 在你程序文件的入口加載自定義logging配置 demo()
三、Django日志配置文件
# logging_config.py # 學(xué)習(xí)中遇到問題沒人解答?小編創(chuàng)建了一個Python學(xué)習(xí)交流群:711312441 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'standard': { 'format': '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' '[%(levelname)s][%(message)s]' }, 'simple': { 'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' }, 'collect': { 'format': '%(message)s' } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { # 打印到終端的日志 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'simple' }, # 打印到文件的日志,收集info及以上的日志 'default': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自動切 'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 'backupCount': 3, 'formatter': 'standard', 'encoding': 'utf-8', }, # 打印到文件的日志:收集錯誤及以上的日志 'error': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自動切 'filename': os.path.join(BASE_LOG_DIR, "xxx_err.log"), # 日志文件 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 'backupCount': 5, 'formatter': 'standard', 'encoding': 'utf-8', }, # 打印到文件的日志 'collect': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自動切 'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"), 'maxBytes': 1024 * 1024 * 5, # 日志大小 5M 'backupCount': 5, 'formatter': 'collect', 'encoding': "utf-8" } }, 'loggers': { # logging.getLogger(__name__)拿到的logger配置 '': { 'handlers': ['default', 'console', 'error'], 'level': 'DEBUG', 'propagate': True, }, # logging.getLogger('collect')拿到的logger配置 'collect': { 'handlers': ['console', 'collect'], 'level': 'INFO', } }, } # ----------- # 用法:拿到倆個logger logger = logging.getLogger(__name__) # 線上正常的日志 collect_logger = logging.getLogger("collect") # 領(lǐng)導(dǎo)說,需要為領(lǐng)導(dǎo)們單獨(dú)定制領(lǐng)導(dǎo)們看的日志
到此這篇關(guān)于一文詳解Python中l(wèi)ogging模塊的用法的文章就介紹到這了,更多相關(guān)Python logging模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python用requests-html爬取網(wǎng)頁的實(shí)現(xiàn)
本文主要介紹了Python用requests-html爬取網(wǎng)頁的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07python區(qū)塊鏈實(shí)現(xiàn)簡版網(wǎng)絡(luò)
這篇文章主要為大家介紹了python區(qū)塊鏈實(shí)現(xiàn)簡版網(wǎng)絡(luò)的詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05基于Python實(shí)現(xiàn)在控制臺查看excel的內(nèi)容
這篇文章主要為大家詳細(xì)介紹了如何基于Python實(shí)現(xiàn)在控制臺查看excel的內(nèi)容,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12python?包實(shí)現(xiàn)JSON?輕量數(shù)據(jù)操作
這篇文章主要介紹了python?包實(shí)現(xiàn)JSON?輕量數(shù)據(jù)操作,文章介紹內(nèi)容首先將對象轉(zhuǎn)為json字符串展開主題詳細(xì)內(nèi)容需要的小伙伴可以參考一下2022-04-04Python re.sub 反向引用的實(shí)現(xiàn)
反向引用指的是在指定替換結(jié)果的過程中,可以引用原始字符串中的匹配到內(nèi)容,本文主要介紹了反向引用的設(shè)置方法,感興趣的可以了解一下2021-07-07關(guān)于DataFrame中某列值的替換map(dict)
這篇文章主要介紹了關(guān)于DataFrame中某列值的替換map(dict),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Python實(shí)現(xiàn)獲取彈幕的兩種方式分享
彈幕可以給觀眾一種“實(shí)時互動”的錯覺,在相同時刻發(fā)送的彈幕基本上也具有相同的主題,在參與評論時就會有與其他觀眾同時評論的錯覺。本文為大家總結(jié)了兩個Python獲取彈幕的方法,希望對大家有所幫助2023-03-03