mitmproxy/mitmproxy/addons/errorcheck.py
Nicolas Jeker d72b92bdff
Show exception and stack trace on startup errors (#6491)
#### Description

It's hard to debug errors raised in addon scripts during startup as only
a generic message is output on the console. Using logger.format() to
format errors that occurred during startup instead of only displaying
the LogRecord.msg improves the output if an exception is present by
showing the stack trace. An additional newline was added for better
readability.

Comparison with the load_error.py test script, before:

    $ mitmproxy -s test/mitmproxy/data/addonscripts/load_error.py
    Error logged during startup: Addon error:

After:

    $ mitmproxy -s test/mitmproxy/data/addonscripts/load_error.py
    Error logged during startup:
    Addon error:
    Traceback (most recent call last):
File "test/mitmproxy/data/addonscripts/load_error.py", line 2, in load
        raise ValueError()
    ValueError

Relates to issue #5935 and PR #6020

#### Checklist

 - [ ] I have updated tests where applicable.
- I think the value of extending `test_errorcheck.py` for this behavior
is low and tightly couples the test to `logger.format()`
 - [ ] I have added an entry to the CHANGELOG.
- #6020 didn't introduce a changelog entry, so I figured this won't need
one either
2023-11-18 10:03:50 +01:00

48 lines
1.5 KiB
Python

import asyncio
import logging
import sys
from mitmproxy import log
class ErrorCheck:
"""Monitor startup for error log entries, and terminate immediately if there are some."""
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()
def finish(self):
self.logger.uninstall()
async def shutdown_if_errored(self):
# don't run immediately, wait for all logging tasks to finish.
await asyncio.sleep(0)
if self.logger.has_errored:
plural = "s" if len(self.logger.has_errored) > 1 else ""
if self.repeat_errors_on_stderr:
msg = "\n".join(self.logger.format(r) for r in self.logger.has_errored)
print(f"Error{plural} logged during startup:\n{msg}", file=sys.stderr)
else:
print(
f"Error{plural} logged during startup, exiting...", file=sys.stderr
)
sys.exit(1)
class ErrorCheckHandler(log.MitmLogHandler):
def __init__(self) -> None:
super().__init__(logging.ERROR)
self.has_errored: list[logging.LogRecord] = []
def emit(self, record: logging.LogRecord) -> None:
self.has_errored.append(record)