From 69b9ab31642bf51be03f56796f4743bef587bd83 Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Tue, 27 Dec 2022 12:02:23 +0100 Subject: [PATCH] Truncate long log lines unless --verbose given --- toot/logging.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/toot/logging.py b/toot/logging.py index e612020..7634a87 100644 --- a/toot/logging.py +++ b/toot/logging.py @@ -1,9 +1,12 @@ import json +import sys from logging import getLogger logger = getLogger('toot') +VERBOSE = "--verbose" in sys.argv + def censor_secrets(headers): def _censor(k, v): @@ -14,6 +17,13 @@ def censor_secrets(headers): 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 + + def log_request(request): logger.debug(">>> \033[32m{} {}\033[0m".format(request.method, request.url)) @@ -22,10 +32,12 @@ def log_request(request): logger.debug(">>> HEADERS: \033[33m{}\033[0m".format(headers)) if request.data: - logger.debug(">>> DATA: \033[33m{}\033[0m".format(request.data)) + data = truncate(request.data) + logger.debug(">>> DATA: \033[33m{}\033[0m".format(data)) if request.json: - logger.debug(">>> JSON: \033[33m{}\033[0m".format(json.dumps(request.json))) + data = truncate(json.dumps(request.json)) + logger.debug(">>> JSON: \033[33m{}\033[0m".format(data)) if request.files: logger.debug(">>> FILES: \033[33m{}\033[0m".format(request.files)) @@ -35,12 +47,14 @@ def log_request(request): def log_response(response): + content = truncate(response.content.decode()) + if response.ok: logger.debug("<<< \033[32m{}\033[0m".format(response)) - logger.debug("<<< \033[33m{}\033[0m".format(response.content.decode())) + logger.debug("<<< \033[33m{}\033[0m".format(content)) else: logger.debug("<<< \033[31m{}\033[0m".format(response)) - logger.debug("<<< \033[31m{}\033[0m".format(response.content.decode())) + logger.debug("<<< \033[31m{}\033[0m".format(content)) def log_debug(*msgs):