Last active
March 21, 2017 22:29
-
-
Save DavidAntliff/cce5967be895cc1c548bbe5616437219 to your computer and use it in GitHub Desktop.
Python: install custom logging handlers for stdout and stderr based on --debug/--verbose flags
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import sys | |
def init_logging(name, log_level): | |
# install handlers for stdout (DEBUG, INFO) and stderr (WARNING, ERROR) | |
# http://stackoverflow.com/a/16066513/143397 | |
logger = logging.getLogger(name) | |
logger.setLevel(log_level) | |
class DebugFilter(logging.Filter): | |
def filter(self, rec): | |
return rec.levelno in (logging.DEBUG,) | |
formatter = logging.Formatter("%(levelname)s:%(name)s:%(message)s", None) | |
# debug uses a special format: | |
debug_handler = logging.StreamHandler(sys.stdout) | |
debug_handler.setLevel(logging.DEBUG) | |
debug_handler.addFilter(DebugFilter()) | |
debug_handler.setFormatter(formatter) | |
class InfoFilter(logging.Filter): | |
def filter(self, rec): | |
return rec.levelno in (logging.INFO,) | |
# info uses default format: | |
info_handler = logging.StreamHandler(sys.stdout) | |
info_handler.setLevel(logging.DEBUG) | |
info_handler.addFilter(InfoFilter()) | |
h2 = logging.StreamHandler() | |
h2.setLevel(logging.WARNING) | |
h2.setFormatter(formatter) | |
logger.addHandler(debug_handler) | |
logger.addHandler(info_handler) | |
logger.addHandler(h2) | |
return logger | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-d', '--debug', action="store_const", dest="loglevel", const=logging.DEBUG, default=logging.WARNING, help="Show debug output") | |
parser.add_argument('-v', '--verbose', action="store_const", dest="loglevel", const=logging.INFO, help="Show more output") | |
args = parser.parse_args() | |
# set up logging on root logger | |
init_logging(None, args.loglevel) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment