简体   繁体   中英

How to use loguru with standard loggers?

I would like to use Loguru to intercept loggers from other modules.

Could anyone of you tell how to approach this topic, please?

Example:

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')

Execution:

$ 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

Answering explicitly...

You want to redirect requests logging through loguru . As mentioned in the comments, you can use:

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

However, it's also worth mentioning that decorating functions with logger.catch() will vastly improve error tracebacks should anything happen during script execution.

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/")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM