1
0
mirror of https://github.com/ihabunek/toot synced 2024-12-23 15:37:47 +01:00
Toot-Mastodon-CLI-TUI-clien.../toot/logging.py

68 lines
1.7 KiB
Python
Raw Normal View History

import json
import sys
2017-12-30 13:06:24 +01:00
from logging import getLogger
2023-11-21 10:07:36 +01:00
from requests import Request, RequestException, Response
2023-02-04 09:01:56 +01:00
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
VERBOSE = "--verbose" in sys.argv
2017-12-30 13:06:24 +01: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 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:
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:
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:
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-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")
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-11-21 10:07:36 +01:00
def log_request_exception(request: Request, ex: RequestException):
logger.debug(f" <-- {request.method} {_url(request)} Exception: {ex}")
2023-02-04 09:01:56 +01:00
def _url(request):
url = request.url
if request.params:
url += f"?{urlencode(request.params)}"
return url