介紹一個(gè)最省心的 Python 日志框架
↑?關(guān)注 + 星標(biāo)?,每天學(xué)Python新技能
后臺(tái)回復(fù)【大禮包】送你Python自學(xué)大禮包
安裝
這個(gè)庫(kù)的安裝方式很簡(jiǎn)單,直接使用 pip 就可以,我使用 Python 3 版本,安裝命令如下:
pip3?install?loguru
小試牛刀
安裝完畢之后,我們就可以使用了,最簡(jiǎn)單的使用方式:
from?loguru?import?logger
logger.debug('this?is?a?debug?message')
無需任何配置,即取即用。上例是打印一條 debug 級(jí)別的日志,輸出結(jié)果如下:
2021-03-16?22:17:23.640?|?DEBUG????|?__main__::8?-?this?is?a?debug?message
這條輸出日志信息包含了日期、時(shí)間、日志級(jí)別、日志代碼行數(shù)以及日志內(nèi)容信息。可以說最基本的內(nèi)容都囊括了,當(dāng)然你還可以打印 warning、info、error、critical、success 等級(jí)別。輸出的日志在 console 中還帶有高亮顏色,并且每個(gè)級(jí)別的日志顏色不一樣,簡(jiǎn)直不要太酷!
日志文件
寫文件
在loguru中,輸出日志文件只需要一個(gè) add() 函數(shù)即可:
logger.add('hello.log')
logger.debug('i?am?in?log?file')
這時(shí)候,在 console 中會(huì)正常打印日志信息,在同級(jí)目錄下會(huì)生成一個(gè)日志文件 hello.log ,我們打開日志文件,可以看到內(nèi)容如下:
2021-03-16?21:20:31.460?|?DEBUG????|?__main__::12?-?i?am?in?log?file
當(dāng)然,我們還可以加一些參數(shù),來指定文件中日志輸出的格式、級(jí)別:
log?=?logger.add('world.log',?format="{time}?|?{level}?|?{message}",?level="INFO")
logger.debug('i?am?debug?message')
logger.info('i?am?info?message')
對(duì)應(yīng)的文件輸出信息如下:
2021-03-16T22:47:53.226998+0800?|?INFO?|?i?am?info?message
我們?cè)O(shè)置了文件只記錄 info 級(jí)別的信息,所以 debug 級(jí)別的日志信息并沒有寫入日志文件。
我們也可以給日志文件名稱加信息:
logger.add('hello_{time}.log')
上面的代碼運(yùn)行后,會(huì)生成一個(gè)帶時(shí)間的日志文件。
停止寫入文件
當(dāng)我們不再需要將日志寫入文件時(shí),我們隨時(shí)可以停止:
id?=?logger.add('world.log',?format="{time}?|?{level}?|?{message}",?level="INFO")
logger.info('this?is?a?info?message')
logger.remove(id)
logger.info('this?is?another?info?message')
add() 方法會(huì)返回一個(gè)日志文件的 id ,當(dāng)我們需要停止寫入信息時(shí),我們使用 remove() 方法,傳入 id ,即可。上面代碼運(yùn)行后,日志文件記錄的信息如下:
2021-03-16T22:47:53.227389+0800?|?INFO?|?this?is?a?info?message
在調(diào)用 remove() 方法后,其后面的日志信息并沒有寫入日志文件中。
滾動(dòng)記錄日志文件
我們可以配置 rotation 參數(shù),來指定日志文件的生成方式,跟通常的日志記錄一樣,我們可以設(shè)置按照文件大小、時(shí)間、日期等來指定生成策略。
#?超過200M就新生成一個(gè)文件
logger.add("size.log",?rotation="200?MB")
#?每天中午12點(diǎn)生成一個(gè)新文件
logger.add("time.log",?rotation="12:00")
#?一周生成一個(gè)新文件
logger.add("size.log",?rotation="1?week")
指定日志文件的有效期
我們還可以通過 retention 參數(shù)來指定日志文件的保留時(shí)長(zhǎng):
logger.add("file.log",?retention="30?days")?
通過上面的配置,可以指定日志文件最多保留30天,30天之前的日志文件就會(huì)被清理掉。
配置壓縮文件
為了節(jié)省空間,我們可能存在壓縮日志文件的需求,這個(gè) loguru 也可以實(shí)現(xiàn):
logger.add("file.log",?compression="zip")?
通過上面的配置,我們指定了日志文件的壓縮格式為 zip 。
異常捕獲
loguru 不僅可以記錄日志,還可以捕獲異常信息,這個(gè)可以幫助我們更好地追溯錯(cuò)誤原因。
在 loguru 模塊中,我們通常有兩種異常捕獲方式:通過 catch 裝飾器捕獲和通過 exception 方法捕獲。
catch 裝飾器捕獲異常
我們來看一個(gè)例子:
@logger.catch
def?a_function(x):
????return?1?/?x
a_function(0)
輸出信息如下:
021-03-16?23:10:28.124?|?ERROR????|?__main__::32?-?An?error?has?been?caught?in?function?'' ,?process?'MainProcess'?(25939),?thread?'MainThread'?(140735895298944):
Traceback?(most?recent?call?last):
??File?"/Users/cxhuan/Library/Application?Support/JetBrains/IntelliJIdea2020.3/plugins/python/helpers/pydev/pydevconsole.py",?line?483,?in?
????pydevconsole.start_client(host,?port)
????│????????????│????????????│?????└?62146
????│????????????│????????????└?'127.0.0.1'
????│????????????└?<function?start_client?at?0x10fd596a8>
????└?'pydevconsole'?from?'/Users/cxhuan/Library/Application?Support/JetBrains/IntelliJIdea2020.3/plugins/python/helpers/py...
??
????......
??
>?File?"/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py",?line?32,?in?
????a_function(0)
????└?
??File?"/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py",?line?30,?in?a_function
????return?1?/?x
???????????????└?0
ZeroDivisionError:?division?by?zero
上面的代碼中,我特意造了一個(gè) 1 除以 0 的異常,我們可以看到日志輸出信息非常詳細(xì),將每一步調(diào)用的錯(cuò)誤信息都詳細(xì)的列出來,并且還把參數(shù)的值也打印出來了,還有非常直觀的指向性,簡(jiǎn)直是異常分析神器!
exception 方法捕獲異常
我們直接看例子:
def?b_function1(x):
????try:
????????return?1?/?x
????except?ZeroDivisionError:
????????logger.exception("exception!!!")
b_function1(0)
運(yùn)行上面代碼,輸出信息如下:
2021-03-16?23:16:07.602?|?ERROR????|?__main__:b_function1:40?-?exception!!!
Traceback?(most?recent?call?last):
??File?"/Users/cxhuan/Library/Application?Support/JetBrains/IntelliJIdea2020.3/plugins/python/helpers/pydev/pydevconsole.py",?line?483,?in?
????pydevconsole.start_client(host,?port)
????│????????????│????????????│?????└?62254
????│????????????│????????????└?'127.0.0.1'
????│????????????└?0x118d216a8>
????└?'pydevconsole'?from?'/Users/cxhuan/Library/Application?Support/JetBrains/IntelliJIdea2020.3/plugins/python/helpers/py...
??File?"/Users/cxhuan/Library/Application?Support/JetBrains/IntelliJIdea2020.3/plugins/python/helpers/pydev/pydevconsole.py",?line?411,?in?start_client
????process_exec_queue(interpreter)
????│??????????????????└?<_pydev_bundle.pydev_ipython_console.InterpreterInterface?object?at?0x118d36240>
????└?????0x118d21400>
????
????......
????
??File?"/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py",?line?42,?in?
????b_function1(0)
????└?
>?File?"/Users/cxhuan/Documents/python_workspace/mypy/loguru/logurustudy.py",?line?38,?in?b_function1
????return?1?/?x
???????????????└?0
ZeroDivisionError:?division?by?zero
同樣地,也是很詳細(xì)和直觀地打印了錯(cuò)誤詳情。
總結(jié)
有需求就有實(shí)現(xiàn),但是能把需求實(shí)現(xiàn)得這么優(yōu)雅、簡(jiǎn)潔的,我只服這個(gè) loguru 的作者。而且還附加了許多非常有用的功能,簡(jiǎn)直是個(gè)鬼才!如果你覺得今天分享的神器有用,點(diǎn)個(gè)“在看”支持一下吧!


