mirror of
https://github.com/vee1e/mitmproxy.git
synced 2026-09-01 10:18:26 +00:00
mitmproxy previously used a homegrown logging mechanism based around
`mitmproxy.ctx.log` and the `add_log` hook. This worked well for everything
we control, but does not work outside the mitmproxy universe.
For now we have simply ignored logging in e.g. tornado or h2, but with the
upcoming introduction of mitmproxy_wireguard we now have a dependency
on some Rust/PyO3 code for which we definitely want logs, but which also
cannot easily be changed to use our homegrown logging (PyO3 does the heavy
lifting to add interoperability with stdlib logging). Long story short,
we want to introduce a log handler for stdlib logging.
Now there are two ways how such a handler could operate:
1. We could build a handler that forwards all stdlib log events
into our homegrown mechanism.
2. We embrace stdlib's logging as the correct way to do things,
and get rid of our homegrown stuff.
This PR follows the second approach by removing the `add_log` hook and
rewriting the `TermLog` and `EventStore` addons to listen for stdlib log records.
This means that all `mitmproxy.ctx.log.info` events are now simply `logging.info` etc.
One upside of this approach is that many parts of the codebase now don't depend
on the existence of `mitmproxy.ctx` and we can use off-the-shelf things like pytest's
`caplog`. We can also now better colorize log output and/or add timestamps.
27 lines
1 KiB
Python
27 lines
1 KiB
Python
"""
|
|
Make events hooks non-blocking using async or @concurrent
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
|
|
import time
|
|
|
|
from mitmproxy.script import concurrent
|
|
|
|
|
|
# Hooks can be async, which allows the hook to call async functions and perform async I/O
|
|
# without blocking other requests. This is generally preferred for new addons.
|
|
async def request(flow):
|
|
logging.info(f"handle request: {flow.request.host}{flow.request.path}")
|
|
await asyncio.sleep(5)
|
|
logging.info(f"start request: {flow.request.host}{flow.request.path}")
|
|
|
|
|
|
# Another option is to use @concurrent, which launches the hook in its own thread.
|
|
# Please note that this generally opens the door to race conditions and decreases performance if not required.
|
|
# Rename the function below to request(flow) to try it out.
|
|
@concurrent # Remove this to make it synchronous and see what happens
|
|
def request_concurrent(flow):
|
|
logging.info(f"handle request: {flow.request.host}{flow.request.path}")
|
|
time.sleep(5)
|
|
logging.info(f"start request: {flow.request.host}{flow.request.path}")
|