termlog: let click figure out stdout/stderr (#4679)

passing sys.stdout to click does not work under some circumstances.
For example, we cannot `click.echo("\u2026")` from pyinstaller binaries in a Docker container
with `file=sys.stdout`. Instead, we shall pass `err`, which somehow works.
This commit is contained in:
Maximilian Hils 2021-07-15 09:55:57 +02:00 committed by GitHub
parent aee4df7c4a
commit a78069f907
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 20 deletions

View File

@ -1,7 +1,6 @@
import itertools
import shutil
import sys
from typing import Optional, TextIO, Union
from typing import IO, Optional, Union
import click
@ -31,10 +30,10 @@ def colorful(line, styles):
class Dumper:
def __init__(self, outfile=sys.stdout, errfile=sys.stderr):
def __init__(self, outfile=None, errfile=None):
self.filter: Optional[flowfilter.TFilter] = None
self.outfp: TextIO = outfile
self.errfp: TextIO = errfile
self.outfp: Optional[IO] = outfile
self.errfp: Optional[IO] = errfile
def load(self, loader):
loader.add_option(
@ -72,12 +71,12 @@ class Dumper:
def echo(self, text: str, ident=None, **style):
if ident:
text = indent(ident, text)
click.secho(text, file=self.outfp, **style)
click.secho(text, file=self.outfp, err=False, **style)
if self.outfp:
self.outfp.flush()
def echo_error(self, text: str, **style):
click.secho(text, file=self.errfp, **style)
click.secho(text, file=self.errfp, err=True, **style)
if self.errfp:
self.errfp.flush()

View File

@ -1,18 +1,14 @@
import sys
from typing import IO, Optional
import click
from mitmproxy import log
from mitmproxy import ctx
# These get over-ridden by the save execution context. Keep them around so we
# can log directly.
realstdout = sys.stdout
realstderr = sys.stderr
class TermLog:
def __init__(self, outfile=None):
self.outfile = outfile
self.outfile: Optional[IO] = outfile
def load(self, loader):
loader.add_option(
@ -22,15 +18,10 @@ class TermLog:
)
def add_log(self, e):
if log.log_tier(e.level) == log.log_tier("error"):
outfile = self.outfile or realstderr
else:
outfile = self.outfile or realstdout
if log.log_tier(ctx.options.termlog_verbosity) >= log.log_tier(e.level):
click.secho(
e.msg,
file=outfile,
file=self.outfile,
fg=dict(error="red", warn="yellow",
alert="magenta").get(e.level),
dim=(e.level == "debug"),