diff options
author | Aldo Cortesi <aldo@nullcube.com> | 2015-05-30 17:43:01 +1200 |
---|---|---|
committer | Aldo Cortesi <aldo@nullcube.com> | 2015-05-30 17:43:01 +1200 |
commit | a09f3e06c36f440b9975cbdb8379734eae9f47cc (patch) | |
tree | 51758aa1fb09962f64cbd46ff07ebe37f0fcc07e /libpathod/log.py | |
parent | 4ed5043c67848bf717e48bc509d959422c8faeb6 (diff) | |
download | mitmproxy-a09f3e06c36f440b9975cbdb8379734eae9f47cc.tar.gz mitmproxy-a09f3e06c36f440b9975cbdb8379734eae9f47cc.tar.bz2 mitmproxy-a09f3e06c36f440b9975cbdb8379734eae9f47cc.zip |
Factor logger out of pathoc, use it in pathod as well.
Diffstat (limited to 'libpathod/log.py')
-rw-r--r-- | libpathod/log.py | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/libpathod/log.py b/libpathod/log.py new file mode 100644 index 00000000..67898dd1 --- /dev/null +++ b/libpathod/log.py @@ -0,0 +1,57 @@ +import netlib.utils +import netlib.tcp +import netlib.http + + +class Log: + def __init__(self, fp, hex, rfile, wfile): + self.lines = [] + self.fp = fp + self.suppressed = False + self.hex = hex + self.rfile, self.wfile = rfile, wfile + + def __enter__(self): + if self.wfile: + self.wfile.start_log() + if self.rfile: + self.rfile.start_log() + return self + + def __exit__(self, exc_type, exc_value, traceback): + wlog = self.wfile.get_log() if self.wfile else None + rlog = self.rfile.get_log() if self.rfile else None + if self.suppressed or not self.fp: + return + if wlog: + self("Bytes written:") + self.dump(wlog, self.hex) + if rlog: + self("Bytes read:") + self.dump(rlog, self.hex) + if exc_type == netlib.tcp.NetLibTimeout: + self("Timeout") + elif exc_type in ( + netlib.tcp.NetLibDisconnect, + netlib.http.HttpErrorConnClosed + ): + self("Disconnected") + elif exc_type == netlib.http.HttpError: + self("HTTP Error: %s" % exc_value.message) + self.fp.write("\n".join(self.lines)) + self.fp.write("\n") + self.fp.flush() + + def suppress(self): + self.suppressed = True + + def dump(self, data, hexdump): + if hexdump: + for line in netlib.utils.hexdump(data): + self("\t%s %s %s" % line) + else: + for i in netlib.utils.cleanBin(data).split("\n"): + self("\t%s" % i) + + def __call__(self, line): + self.lines.append(line) |