witchie/toot/logging.py

64 lines
1.5 KiB
Python
Raw Normal View History

import json
import sys
2017-12-30 12:06:24 +00:00
from logging import getLogger
2023-02-04 08:01:56 +00:00
from requests import Request, Response
from urllib.parse import urlencode
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00:00
logger = getLogger("toot")
2017-12-30 12:06:24 +00:00
VERBOSE = "--verbose" in sys.argv
2017-12-30 12:06:24 +00: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()}
def truncate(line):
if not VERBOSE and len(line) > 100:
return line[:100] + ""
return line
2023-02-04 08:01:56 +00:00
def log_request(request: Request):
logger.debug(f" --> {request.method} {_url(request)}")
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00:00
if VERBOSE and request.headers:
headers = censor_secrets(request.headers)
2023-02-04 08:01:56 +00:00
logger.debug(f" --> HEADERS: {headers}")
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00:00
if VERBOSE and request.data:
data = truncate(request.data)
2023-02-04 08:01:56 +00:00
logger.debug(f" --> DATA: {data}")
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00:00
if VERBOSE and request.json:
data = truncate(json.dumps(request.json))
2023-02-04 08:01:56 +00:00
logger.debug(f" --> JSON: {data}")
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00:00
if VERBOSE and request.files:
logger.debug(f" --> FILES: {request.files}")
2017-12-30 12:06:24 +00:00
2023-02-04 08:01:56 +00: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")
2023-02-04 08:01:56 +00:00
if VERBOSE and response.content:
content = truncate(response.content.decode())
logger.debug(f" <-- {content}")
2018-01-14 14:34:41 +00:00
2023-02-04 08:01:56 +00:00
def _url(request):
url = request.url
if request.params:
url += f"?{urlencode(request.params)}"
return url