一文詳解Python中l(wèi)ogging模塊的用法
一、低配logging
日志總共分為以下五個(gè)級(jí)別,這個(gè)五個(gè)級(jí)別自下而上進(jìn)行匹配 debug-->info-->warning-->error-->critical,默認(rèn)最低級(jí)別為warning級(jí)別。
1.v1
import logging
logging.debug('調(diào)試信息')
logging.info('正常信息')
logging.warning('警告信息')
logging.error('報(bào)錯(cuò)信息')
logging.critical('嚴(yán)重錯(cuò)誤信息')WARNING:root:警告信息
ERROR:root:報(bào)錯(cuò)信息
CRITICAL:root:嚴(yán)重錯(cuò)誤信息
v1版本無法指定日志的級(jí)別;無法指定日志的格式;只能往屏幕打印,無法寫入文件。因此可以改成下述的代碼。
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('報(bào)錯(cuò)信息') # 40
logging.critical('嚴(yán)重錯(cuò)誤信息') # 50可在logging.basicConfig()函數(shù)中可通過具體參數(shù)來更改logging模塊默認(rèn)行為,可用參數(shù)有:
- filename:用指定的文件名創(chuàng)建FiledHandler(后邊會(huì)具體講解handler的概念),這樣日志會(huì)被存儲(chǔ)在指定的文件中。
- filemode:文件打開方式,在指定了filename時(shí)使用這個(gè)參數(shù),默認(rèn)值為“a”還可指定為“w”。
- format:指定handler使用的日志顯示格式。
- datefmt:指定日期時(shí)間格式。
- level:設(shè)置rootlogger(后邊會(huì)講解具體概念)的日志級(jí)別
- stream:用指定的stream創(chuàng)建StreamHandler??梢灾付ㄝ敵龅絪ys.stderr,sys.stdout或者文件,默認(rèn)為sys.stderr。若同時(shí)列出了filename和stream兩個(gè)參數(shù),則stream參數(shù)會(huì)被忽略。
format參數(shù)中可能用到的格式化串:
- %(name)s Logger的名字
- %(levelno)s 數(shù)字形式的日志級(jí)別
- %(levelname)s 文本形式的日志級(jí)別
- %(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)前時(shí)間,用UNIX標(biāo)準(zhǔn)的表示時(shí)間的浮 點(diǎn)數(shù)表示
- %(relativeCreated)d 輸出日志信息時(shí)的,自Logger創(chuàng)建以 來的毫秒數(shù)
- %(asctime)s 字符串形式的當(dāng)前時(shí)間。默認(rèn)格式是 “2003-07-08 16:49:45,896”。逗號(hào)后面的是毫秒
- %(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è)置日志級(jí)別
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(sm)
# 設(shè)置日志級(jí)別,可以在兩個(gè)關(guān)卡進(jìn)行設(shè)置logger與handler
# logger是第一級(jí)過濾,然后才能到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.配置日志文件
以上三個(gè)版本的日志只是為了引出我們下面的日志配置文件
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)建一個(gè)
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')
'': {
# 這里把上面定義的兩個(gè)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__) # 生成一個(gè)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)建了一個(gè)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', # 保存到文件,自動(dòng)切
'filename': os.path.join(BASE_LOG_DIR, "xxx_info.log"), # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M
'backupCount': 3,
'formatter': 'standard',
'encoding': 'utf-8',
},
# 打印到文件的日志:收集錯(cuò)誤及以上的日志
'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自動(dòng)切
'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', # 保存到文件,自動(dòng)切
'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',
}
},
}
# -----------
# 用法:拿到倆個(gè)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實(shí)現(xiàn)將html表格轉(zhuǎn)換成CSV文件的方法
這篇文章主要介紹了python實(shí)現(xiàn)將html表格轉(zhuǎn)換成CSV文件的方法,涉及Python操作csv文件的相關(guān)技巧,需要的朋友可以參考下2015-06-06
使用python將一個(gè)文件分配到指定的多個(gè)文件夾
這篇文章主要為大家詳細(xì)介紹了如何使用python將一個(gè)文件分配到指定的多個(gè)文件夾,也就說將一個(gè)文件分配到一個(gè)母文件夾下的所有的子文件夾,感興趣的可以了解下2025-01-01
如何利用opencv對拍攝圖片進(jìn)行文字識(shí)別
在有些工程中有時(shí)候我們需要對圖片文字識(shí)別,下面這篇文章主要給大家介紹了關(guān)于如何利用opencv對拍攝圖片進(jìn)行文字識(shí)別的相關(guān)資料,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03
matplotlib繪制雷達(dá)圖的基本配置(萬能模板案例)
本文主要介紹了matplotlib繪制雷達(dá)圖的基本配置(萬能模板案例),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
Python計(jì)數(shù)器collections.Counter用法詳解
本文主要介紹了Python計(jì)數(shù)器collections.Counter用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03
Python開源自動(dòng)化工具Playwright安裝及介紹使用
playwright-python是一個(gè)強(qiáng)大的Python庫,僅用一個(gè)API即可自動(dòng)執(zhí)行Chromium、Firefox、WebKit等主流瀏覽器自動(dòng)化操作,本文就詳細(xì)的介紹一下如何使用,感興趣的可以了解一下2021-12-12
Python生成ubuntu apt鏡像地址實(shí)現(xiàn)
本文主要介紹了Python生成ubuntu apt鏡像地址實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05

