Python日志模塊logging用法
一、概述
步驟
- 創(chuàng)建logger對(duì)象
- 創(chuàng)建handler對(duì)象
- 創(chuàng)建formatter對(duì)象
- 把formatter綁定到handler對(duì)象上
- 把handler對(duì)象綁定到logger對(duì)象上
- 設(shè)置級(jí)別
- 測(cè)試
二、低配logging
日志總共分為以下五個(gè)級(jí)別,這個(gè)五個(gè)級(jí)別自下而上進(jìn)行匹配 debug-->info-->warning-->error-->critical,默認(rèn)最低級(jí)別為warning級(jí)別。
critical=50、error =40 、arning =30、info = 20、debug =10
v1:屏幕輸出
v1版本無法指定日志的級(jí)別;無法指定日志的格式;只能往屏幕打印,無法寫入文件。
import logging
logging.debug('調(diào)試信息')
logging.info('正常信息')
logging.warning('警告信息') # WARNING:root:警告信息
logging.error('報(bào)錯(cuò)信息') # ERROR:root:報(bào)錯(cuò)信息
logging.critical('嚴(yán)重錯(cuò)誤信息') # CRITICAL:root:嚴(yán)重錯(cuò)誤信息v2:輸出到文件
v2版本不能指定字符編碼;只能往文件中打印。
可在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ì)被忽略。
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)試信息') # 2019-11-28 18:25:26 PM - root - DEBUG -run: 調(diào)試信息
logging.info('正常信息') # 2019-11-28 18:25:26 PM - root - INFO -run: 正常信息
logging.warning('警告信息') # 2019-11-28 18:25:26 PM - root - WARNING -run: 警告信息
logging.error('報(bào)錯(cuò)信息') # 2019-11-28 18:25:26 PM - root - ERROR -run: 報(bào)錯(cuò)信息
logging.critical('嚴(yán)重錯(cuò)誤信息') # 2019-11-28 18:25:26 PM - root - CRITICAL -run: 嚴(yán)重錯(cuò)誤信息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:用戶輸出的消息
v3:使用內(nèi)置各種對(duì)象
logging模塊包含四種角色:logger、Filter、Formatter、Handler對(duì)象
- logger:產(chǎn)生日志的對(duì)象
- Filter:過濾日志的對(duì)象
- Formatter:可以定制不同的日志格式對(duì)象,然后綁定給不同的Handler對(duì)象使用,以此來控制不同的Handler的日志格式
- Handler:接收日志然后控制打印到不同的地方,F(xiàn)ileHandler用來打印到文件中,StreamHandler用來打印到終端
import logging
# 1、logger對(duì)象:負(fù)責(zé)產(chǎn)生日志,然后交給Filter過濾,然后交給不同的Handler輸出
logger = logging.getLogger(__file__)
# 2、Filter對(duì)象:不常用,略
# 3、Handler對(duì)象:接收logger傳來的日志,然后控制輸出
h1 = logging.FileHandler('t1.log') # 打印到文件
h2 = logging.FileHandler('t2.log') # 打印到文件
sm = logging.StreamHandler() # 打印到終端
# 4、Formatter對(duì)象:日志格式
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對(duì)象綁定格式
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、測(cè)試
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("中文測(cè)試開始。。。")
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("中文測(cè)試結(jié)束。。。")
if __name__ == "__main__":
my_logging.load_my_logging_cfg() # 在你程序文件的入口加載自定義logging配置
demo()四、Django日志配置文件
Django(發(fā)音:[`d?æ?ɡ??])是一個(gè)開放源代碼的Web應(yīng)用框架,由Python寫成。采用了MTV的框架模式,即模型M,視圖V和模版T。
# logging_config.py
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日志模塊的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python arcpy練習(xí)之面要素重疊拓?fù)錂z查
今天小編就為大家分享一篇Python ArcPy的面要素重疊拓?fù)錂z查,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-09-09
利用Python實(shí)現(xiàn)自動(dòng)掃雷小腳本
這篇文章主要介紹了利用Python實(shí)現(xiàn)自動(dòng)掃雷小腳本,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12
pyqt 實(shí)現(xiàn)為長(zhǎng)內(nèi)容添加滑輪 scrollArea
今天小編就為大家分享一篇pyqt 實(shí)現(xiàn)為長(zhǎng)內(nèi)容添加滑輪 scrollArea,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python爬取數(shù)據(jù)保存為Json格式的代碼示例
今天小編就為大家分享一篇關(guān)于Python爬取數(shù)據(jù)保存為Json格式的代碼示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-04-04
執(zhí)行python腳本并傳入json數(shù)據(jù)格式參數(shù)方式
這篇文章主要介紹了執(zhí)行python腳本并傳入json數(shù)據(jù)格式參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09

