簡體   English   中英

如何將 loguru 與標准記錄器一起使用?

[英]How to use loguru with standard loggers?

我想使用Loguru來攔截來自其他模塊的記錄器。

請問你們中的任何人都可以告訴如何處理這個話題嗎?

例子:

import logging
import requests
from loguru import logger

logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logger_requests = logging.getLogger('requests')
logger_requests.setLevel(logging.DEBUG)

logger.debug('Message through loguru')
requests.get('https://stackoverflow.com')

執行:

$ python test_logger.py  > /dev/null 
2021-03-23 19:35:27.141 | DEBUG    | __main__:<module>:10 - Message through loguru
DEBUG:Starting new HTTPS connection (1): stackoverflow.com:443
DEBUG:https://stackoverflow.com:443 "GET / HTTP/1.1" 200 None

明確回答...

您想重定向通過loguru記錄的requests 如評論中所述,您可以使用:

logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)

但是,還值得一提的是,如果在腳本執行期間發生任何事情,使用logger.catch()裝飾函數將大大改善錯誤回溯。

import logging
import sys

import requests
from loguru import logger


class InterceptHandler(logging.Handler):
    """
    Add logging handler to augment python stdlib logging.

    Logs which would otherwise go to stdlib logging are redirected through
    loguru.
    """

    @logger.catch(default=True, onerror=lambda _: sys.exit(1))
    def emit(self, record):
        # Get corresponding Loguru level if it exists.
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        # Find caller from where originated the logged message.
        frame, depth = sys._getframe(6), 6
        while frame and 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())


##########################################################################
# The logger.catch() decorator improves error tracebacks
#     ^^^^^^^^^^^^^^
##########################################################################
@logger.catch(default=True, onerror=lambda _: sys.exit(1))
def requests_http_get(url=None):
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
    logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)

    logger_requests = logging.getLogger('requests')
    logger_requests.setLevel(logging.DEBUG)
    logger.debug('Message through loguru')
    requests.get(url)

if __name__=="__main__":
    requests_http_get("https://stackoverflow.com/")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM