自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

為什么不推薦使用Python原生日志庫(kù)?

開發(fā) 前端
Python自帶的logging我個(gè)人不推介使用,不太Pythonic,而開源的Loguru庫(kù)成為眾多工程師及項(xiàng)目中首選,本期將同時(shí)對(duì)logging及Loguru進(jìn)行使用對(duì)比,希望有所幫助。

包括我在內(nèi)的大多數(shù)人,當(dāng)編寫小型腳本時(shí),習(xí)慣使用print來(lái)debug,肥腸方便,這沒問題,但隨著代碼不斷完善,日志功能一定是不可或缺的,極大程度方便問題溯源以及甩鍋,也是每個(gè)工程師必備技能。

Python自帶的logging我個(gè)人不推介使用,不太Pythonic,而開源的Loguru庫(kù)成為眾多工程師及項(xiàng)目中首選,本期將同時(shí)對(duì)logging及Loguru進(jìn)行使用對(duì)比,希望有所幫助。

快速示例

在logging中,默認(rèn)的日志功能輸出的信息較為有限:

import logging

logger = logging.getLogger(__name__)

def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")

if __name__ == "__main__":
    main()

輸出(logging默認(rèn)日志等級(jí)為warning,故此處未輸出info與debug等級(jí)的信息):

WARNING:root:This is a warning message
ERROR:root:This is an error message

再來(lái)看看loguru,默認(rèn)生成的信息就較為豐富了:

from loguru import logger

def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")

if __name__ == "__main__":
    main()

提供了執(zhí)行時(shí)間、等級(jí)、在哪個(gè)函數(shù)調(diào)用、具體哪一行等信息。

格式化日志

格式化日志允許我們向日志添加有用的信息,例如時(shí)間戳、日志級(jí)別、模塊名稱、函數(shù)名稱和行號(hào)。

在logging中使用%達(dá)到格式化目的:

import logging

# Create a logger and set the logging level
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

logger = logging.getLogger(__name__)

def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")

輸出:

2023-10-18 15:47:30 | INFO | tmp:<module>:186 - This is an info message
2023-10-18 15:47:30 | WARNING | tmp:<module>:187 - This is a warning message
2023-10-18 15:47:30 | ERROR | tmp:<module>:188 - This is an error message

而loguru使用和f-string相同的{}格式,更方便:

from loguru import logger

logger.add(
    sys.stdout,
    level="INFO",
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} - {message}",
)

日志保存

在logging中,實(shí)現(xiàn)日志保存與日志打印需要兩個(gè)額外的類,F(xiàn)ileHandler 和 StreamHandler:

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
    handlers=[
        logging.FileHandler(filename="/your/save/path/info.log", level=logging.INFO),
        logging.StreamHandler(level=logging.DEBUG),
    ],
)

logger = logging.getLogger(__name__)

def main():
    logging.debug("This is a debug message")
    logging.info("This is an info message")
    logging.warning("This is a warning message")
    logging.error("This is an error message")


if __name__ == "__main__":
    main()

但是在loguru中,只需要使用add方法即可達(dá)到目的:

from loguru import logger

logger.add(
    'info.log',
    format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} - {message}",
    level="INFO",
)


def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")


if __name__ == "__main__":
    main()

日志輪換

日志輪換指通過(guò)定期創(chuàng)建新的日志文件并歸檔或刪除舊的日志來(lái)防止日志變得過(guò)大。

在logging中,需要一個(gè)名為 TimedRotatingFileHandler 的附加類,以下代碼示例代表每周切換到一個(gè)新的日志文件 ( when=“WO”, interval=1 ),并保留最多 4 周的日志文件 ( backupCount=4 ):

import logging
from logging.handlers import TimedRotatingFileHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Create a formatter with the desired log format
formatter = logging.Formatter(
    "%(asctime)s | %(levelname)-8s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

file_handler = TimedRotatingFileHandler(
    filename="debug2.log", when="WO", interval=1, backupCount=4
)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)


def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")


if __name__ == "__main__":
    main()

在loguru中,可以通過(guò)將 rotation 和 retention 參數(shù)添加到 add 方法來(lái)達(dá)到目的,如下示例,同樣肥腸方便:

from loguru import logger

logger.add("debug.log", level="INFO", rotation="1 week", retention="4 weeks")


def main():
    logger.debug("This is a debug message")
    logger.info("This is an info message")
    logger.warning("This is a warning message")
    logger.error("This is an error message")


if __name__ == "__main__":
    main()

日志篩選

日志篩選指根據(jù)特定條件有選擇的控制應(yīng)輸出與保存哪些日志信息。

在logging中,實(shí)現(xiàn)該功能需要?jiǎng)?chuàng)建自定義日志過(guò)濾器類:

import logging


logging.basicConfig(
    filename="test.log",
    format="%(asctime)s | %(levelname)-8s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",
    level=logging.INFO,
)


class CustomFilter(logging.Filter):
    def filter(self, record):
        return "Cai Xukong" in record.msg


# Create a custom logging filter
custom_filter = CustomFilter()

# Get the root logger and add the custom filter to it
logger = logging.getLogger()
logger.addFilter(custom_filter)


def main():
    logger.info("Hello Cai Xukong")
    logger.info("Bye Cai Xukong")


if __name__ == "__main__":
    main()

在loguru中,可以簡(jiǎn)單地使用lambda函數(shù)來(lái)過(guò)濾日志:

from loguru import logger

logger.add("test.log", filter=lambda x: "Cai Xukong" in x["message"], level="INFO")


def main():
    logger.info("Hello Cai Xukong")
    logger.info("Bye Cai Xukong")


if __name__ == "__main__":
    main()

捕獲異常

在logging中捕獲異常較為不便且難以調(diào)試,如:

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)s | %(module)s:%(funcName)s:%(lineno)d - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)


def division(a, b):
    return a / b


def nested(c):
    try:
        division(1, c)
    except ZeroDivisionError:
        logging.exception("ZeroDivisionError")


if __name__ == "__main__":
    nested(0)
Traceback (most recent call last):
  File "logging_example.py", line 16, in nested
    division(1, c)
  File "logging_example.py", line 11, in division
    return a / b
ZeroDivisionError: division by zero

上面輸出的信息未提供觸發(fā)異常的c值信息,而在loguru中,通過(guò)顯示包含變量值的完整堆棧跟蹤來(lái)方便用戶識(shí)別:

Traceback (most recent call last):
  File "logging_example.py", line 16, in nested
    division(1, c)
  File "logging_example.py", line 11, in division
    return a / b
ZeroDivisionError: division by zero

值得一提的是,loguru中的catch裝飾器允許用戶捕獲函數(shù)內(nèi)任何錯(cuò)誤,且還會(huì)標(biāo)識(shí)發(fā)生錯(cuò)誤的線程:

from loguru import logger


def division(a, b):
    return a / b


@logger.catch
def nested(c):
    division(1, c)


if __name__ == "__main__":
    nested(0)

OK,作為普通玩家以上功能足以滿足日常日志需求,通過(guò)對(duì)比logging與loguru應(yīng)該讓大家有了直觀感受,哦對(duì)了,loguru如何安裝?

pip install loguru

以上就是本期的全部?jī)?nèi)容,期待點(diǎn)贊在看,我是啥都生,下次再見。

責(zé)任編輯:趙寧寧 來(lái)源: 啥都會(huì)一點(diǎn)的研究生
相關(guān)推薦

2024-11-29 08:20:22

Autowired場(chǎng)景項(xiàng)目

2024-11-12 10:30:54

Docker部署數(shù)據(jù)庫(kù)

2024-06-04 00:10:00

開發(fā)拷貝

2018-11-29 14:30:42

數(shù)據(jù)庫(kù)外鍵約束應(yīng)用程序

2024-09-12 08:32:42

2021-08-23 13:02:50

MySQLJOIN數(shù)據(jù)庫(kù)

2022-01-11 10:29:32

Docker文件掛載

2025-04-29 07:06:20

2021-01-13 09:55:29

try-catch-fJava代碼

2021-07-04 14:19:03

RabbitMQ消息轉(zhuǎn)換

2020-08-31 11:20:53

MySQLuuidid

2024-03-11 11:02:03

Date類JavaAPI

2020-07-02 14:12:52

C++語(yǔ)言編程

2024-07-29 09:03:00

2023-09-27 23:03:01

Java虛擬線程

2020-06-18 10:21:46

Python程序員技術(shù)

2020-02-25 17:04:05

數(shù)據(jù)庫(kù)云原生分布式

2023-10-09 18:39:13

Python代碼

2021-09-08 07:58:58

字節(jié)系統(tǒng)雙寫

2022-12-26 00:00:03

非繼承關(guān)系JDK
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)