[英]Standard library logging plus loguru
假設我正在設置一個腳本或庫,它有一些使用 Python 的標准庫logging
模塊的依賴項,但我想使用loguru
來捕獲所有日志。 我的第一次天真嘗試完全失敗,但我不知道如何繼續。
測試我有兩個文件
main.py
:
from loguru import logger
from base_log import test_func
if __name__ == "__main__":
logger.debug("In main")
test_func()
和base_log.py
:
import logging
logger = logging.getLogger(__name__)
def test_func():
logger.warning("In test_func")
如果我運行main.py
(即python main.py
)然后我得到以下 output:
2020-12-16 10:57:48.269 | DEBUG | __main__:<module>:6 - In main
In test_func
當我期望:
2020-12-16 11:01:34.408 | DEBUG | __main__:<module>:6 - In main
2020-12-16 11:01:34.408 | WARNING | base_log:test_func:9 - In test_func
您可以使用自定義處理程序來攔截發送到 Loguru 接收器的標准日志記錄消息,如此處所述。
main.py
然后看起來像這樣:
import logging
from loguru import logger
from base_log import test_func
class InterceptHandler(logging.Handler):
def emit(self, record):
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage()
)
if __name__ == "__main__":
logging.basicConfig(handlers=[InterceptHandler()], level=0)
logger.debug("In main")
test_func()
Output:
2020-12-16 22:15:55.337 | DEBUG | __main__:<module>:26 - In main
2020-12-16 22:15:55.337 | WARNING | base_log:test_func:7 - In test_func
這應該適用於所有行為良好的庫,這些庫不會將 NullHandler 以外的任何處理程序添加到庫的記錄器中。 rest 可能需要額外的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.