From a78069f907386813225a5b6d3af906a66545e9da Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Thu, 15 Jul 2021 09:55:57 +0200 Subject: [PATCH] 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. --- mitmproxy/addons/dumper.py | 13 ++++++------- mitmproxy/addons/termlog.py | 17 ++++------------- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/mitmproxy/addons/dumper.py b/mitmproxy/addons/dumper.py index 335d80344..92d78ece3 100644 --- a/mitmproxy/addons/dumper.py +++ b/mitmproxy/addons/dumper.py @@ -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() diff --git a/mitmproxy/addons/termlog.py b/mitmproxy/addons/termlog.py index 706f9498a..b4ac300d8 100644 --- a/mitmproxy/addons/termlog.py +++ b/mitmproxy/addons/termlog.py @@ -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"),