0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

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

Posted at

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?