0
Help us understand the problem. What are the problem?

posted at

Loguruでライブラリのログを出力する

Pythonのライブラリが出力するログを活用しよう
をloguruでやる方法

logging版

a.py
import requests
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

try:
    requests.get("https://expired-rsa-dv.ssl.com/")
except requests.exceptions.SSLError:
    logger.info("SSLError")
$ python3 a.py
Starting new HTTPS connection (1): expired-rsa-dv.ssl.com:443
SSLError

loguru版

Want to intercept standard logging messages toward your Loguru sinks?
Standard library logging plus loguru

b.py
import requests
from loguru import logger
import logging

class InterceptHandler(logging.Handler):
    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 = 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())

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

try:
    requests.get("https://expired-rsa-dv.ssl.com/")
except requests.exceptions.SSLError:
    logger.info("SSLError")
$ python3 b.py
2022-04-23 02:59:17.605 | DEBUG    | urllib3.connectionpool:_new_conn:1005 - Starting new HTTPS connection (1): expired-rsa-dv.ssl.com:443
2022-04-23 02:59:18.125 | INFO     | __main__:<module>:27 - SSLError

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
0
Help us understand the problem. What are the problem?