2022-11-22 09:51:09 +01:00
|
|
|
import json
|
2022-12-27 12:02:23 +01:00
|
|
|
import sys
|
2022-11-22 09:51:09 +01:00
|
|
|
|
2017-12-30 13:06:24 +01:00
|
|
|
from logging import getLogger
|
2023-02-04 09:01:56 +01:00
|
|
|
from requests import Request, Response
|
|
|
|
from urllib.parse import urlencode
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
logger = getLogger("toot")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2022-12-27 12:02:23 +01:00
|
|
|
VERBOSE = "--verbose" in sys.argv
|
|
|
|
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2020-05-11 12:46:27 +02:00
|
|
|
def censor_secrets(headers):
|
|
|
|
def _censor(k, v):
|
|
|
|
if k == "Authorization":
|
|
|
|
return (k, "***CENSORED***")
|
|
|
|
return k, v
|
|
|
|
|
|
|
|
return {_censor(k, v) for k, v in headers.items()}
|
|
|
|
|
|
|
|
|
2022-12-27 12:02:23 +01:00
|
|
|
def truncate(line):
|
|
|
|
if not VERBOSE and len(line) > 100:
|
|
|
|
return line[:100] + "…"
|
|
|
|
|
|
|
|
return line
|
|
|
|
|
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
def log_request(request: Request):
|
|
|
|
logger.debug(f" --> {request.method} {_url(request)}")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
if VERBOSE and request.headers:
|
2020-05-11 12:46:27 +02:00
|
|
|
headers = censor_secrets(request.headers)
|
2023-02-04 09:01:56 +01:00
|
|
|
logger.debug(f" --> HEADERS: {headers}")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
if VERBOSE and request.data:
|
2022-12-27 12:02:23 +01:00
|
|
|
data = truncate(request.data)
|
2023-02-04 09:01:56 +01:00
|
|
|
logger.debug(f" --> DATA: {data}")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
if VERBOSE and request.json:
|
2022-12-27 12:02:23 +01:00
|
|
|
data = truncate(json.dumps(request.json))
|
2023-02-04 09:01:56 +01:00
|
|
|
logger.debug(f" --> JSON: {data}")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
if VERBOSE and request.files:
|
|
|
|
logger.debug(f" --> FILES: {request.files}")
|
2017-12-30 13:06:24 +01:00
|
|
|
|
2023-01-19 02:15:37 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
def log_response(response: Response):
|
|
|
|
method = response.request.method
|
|
|
|
url = response.request.url
|
|
|
|
elapsed = response.elapsed.microseconds // 1000
|
|
|
|
logger.debug(f" <-- {method} {url} HTTP {response.status_code} {elapsed}ms")
|
2022-12-27 12:02:23 +01:00
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
if VERBOSE and response.content:
|
|
|
|
content = truncate(response.content.decode())
|
|
|
|
logger.debug(f" <-- {content}")
|
2018-01-14 15:34:41 +01:00
|
|
|
|
|
|
|
|
2023-02-04 09:01:56 +01:00
|
|
|
def _url(request):
|
|
|
|
url = request.url
|
|
|
|
if request.params:
|
|
|
|
url += f"?{urlencode(request.params)}"
|
|
|
|
return url
|