python的強大且簡單日誌庫loguru

一、logging標準日誌庫使用

python寫代碼時,logging模塊最基本的幾行配置,如下:

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

logger.info('this is another debug message')
logger.warning('this is another debug message')
logger.error('this is another debug message')
logger.info('this is another debug message')

二、loguru日誌庫

安裝

pip install loguru 

https://loguru.readthedocs.io/en/stable/api/logger.html

使用:

#!/bin/python

from loguru import logger

logger.debug('this is a debug message')
logger.info('this is another debug message')
logger.warning('this is another debug message')
logger.error('this is another debug message')
logger.info('this is another debug message')
logger.success('this is success message!')
logger.critical('this is critical message!')

不需要配置什麼東西,直接引入一個 logger,然後調用其 debug 方法即可。

如果想要輸出到文件,只需要:

添加一行:

logger.add('my_log.log')

 文件內容爲:

#!/bin/python

from loguru import logger

logger.add("my_log.log")

logger.debug('this is a debug message')
logger.info('this is another debug message')
logger.warning('this is another debug message')
logger.error('this is another debug message')
logger.info('this is another debug message')
logger.success('this is success message!')
logger.critical('this is critical message!')

 查看結果得到:

#cat my_log.log
2021-11-05 10:15:27.780 | DEBUG    | __main__:<module>:7 - this is a debug message
2021-11-05 10:15:27.780 | INFO     | __main__:<module>:8 - this is another debug message
2021-11-05 10:15:27.780 | WARNING  | __main__:<module>:9 - this is another debug message
2021-11-05 10:15:27.780 | ERROR    | __main__:<module>:10 - this is another debug message
2021-11-05 10:15:27.780 | INFO     | __main__:<module>:11 - this is another debug message
2021-11-05 10:15:27.780 | SUCCESS  | __main__:<module>:12 - this is success message!
2021-11-05 10:15:27.780 | CRITICAL | __main__:<module>:13 - this is critical message!

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章