improve ux when errors are logged during startup, fix #5935 (#6020)

This commit is contained in:
Maximilian Hils 2023-03-26 20:14:57 +02:00 committed by GitHub
parent 84b03c06e3
commit 8757757892
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 7 deletions

View File

@ -8,8 +8,14 @@ from mitmproxy import log
class ErrorCheck:
"""Monitor startup for error log entries, and terminate immediately if there are some."""
def __init__(self, log_to_stderr: bool = False) -> None:
self.log_to_stderr = log_to_stderr
repeat_errors_on_stderr: bool
"""
Repeat all errors on stderr before exiting.
This is useful for the console UI, which otherwise swallows all output.
"""
def __init__(self, repeat_errors_on_stderr: bool = False) -> None:
self.repeat_errors_on_stderr = repeat_errors_on_stderr
self.logger = ErrorCheckHandler()
self.logger.install()
@ -21,10 +27,14 @@ class ErrorCheck:
# don't run immediately, wait for all logging tasks to finish.
await asyncio.sleep(0)
if self.logger.has_errored:
if self.log_to_stderr:
plural = "s" if len(self.logger.has_errored) > 1 else ""
plural = "s" if len(self.logger.has_errored) > 1 else ""
if self.repeat_errors_on_stderr:
msg = "\n".join(r.msg for r in self.logger.has_errored)
print(f"Error{plural} on startup: {msg}", file=sys.stderr)
print(f"Error{plural} logged during startup: {msg}", file=sys.stderr)
else:
print(
f"Error{plural} logged during startup, exiting...", file=sys.stderr
)
sys.exit(1)

View File

@ -55,7 +55,7 @@ class ConsoleMaster(master.Master):
readfile.ReadFile(),
consoleaddons.ConsoleAddon(self),
keymap.KeymapConfig(self),
errorcheck.ErrorCheck(log_to_stderr=True),
errorcheck.ErrorCheck(repeat_errors_on_stderr=True),
)
self.window: window.Window | None = None

View File

@ -1,3 +1,5 @@
import logging
import pytest
from mitmproxy.addons.errorcheck import ErrorCheck
@ -13,10 +15,19 @@ def test_errorcheck(tdata, capsys):
tdata.path("mitmproxy/data/addonscripts/load_error.py"),
]
)
assert "Error on startup" in capsys.readouterr().err
assert "Error logged during startup" in capsys.readouterr().err
async def test_no_error():
e = ErrorCheck()
await e.shutdown_if_errored()
e.finish()
async def test_error_message(capsys):
e = ErrorCheck()
logging.error("wat")
logging.error("wat")
with pytest.raises(SystemExit):
await e.shutdown_if_errored()
assert "Errors logged during startup" in capsys.readouterr().err