From 8f6282a91f1a0d86496a981bdb789a6c83f8757c Mon Sep 17 00:00:00 2001 From: Marek Goldmann Date: Tue, 14 Mar 2017 15:52:29 +0100 Subject: [PATCH] Send messages to appropriate streams INFO goes to stdout, everything else goes to stderr Fixes #144 --- docker_squash/cli.py | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/docker_squash/cli.py b/docker_squash/cli.py index cff0773..e59aafc 100644 --- a/docker_squash/cli.py +++ b/docker_squash/cli.py @@ -8,6 +8,19 @@ from docker_squash.version import version +# Source: http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams +class SingleLevelFilter(logging.Filter): + def __init__(self, passlevel, reject): + self.passlevel = passlevel + self.reject = reject + + def filter(self, record): + if self.reject: + return (record.levelno != self.passlevel) + else: + return (record.levelno == self.passlevel) + + class MyParser(argparse.ArgumentParser): def error(self, message): @@ -19,12 +32,21 @@ def error(self, message): class CLI(object): def __init__(self): + handler_out = logging.StreamHandler(sys.stdout) + handler_err = logging.StreamHandler(sys.stderr) + + handler_out.addFilter(SingleLevelFilter(logging.INFO, False)) + handler_err.addFilter(SingleLevelFilter(logging.INFO, True)) + self.log = logging.getLogger() - handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') - handler.setFormatter(formatter) - self.log.addHandler(handler) + + handler_out.setFormatter(formatter) + handler_err.setFormatter(formatter) + + self.log.addHandler(handler_out) + self.log.addHandler(handler_err) def run(self): parser = MyParser(