Created
April 8, 2017 22:13
-
-
Save perrygeo/b8774cbe739141fc8f276e9cd7775155 to your computer and use it in GitHub Desktop.
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 | |
# ----------- Library code ------------------- # | |
logger = logging.getLogger(__name__) | |
# think of this as a global restriction | |
# even if the handlers want access to lower levels, they don't get it | |
logger.setLevel(logging.INFO) | |
# Always attach the null handler | |
logger.addHandler(logging.NullHandler()) | |
# ----------- Application code, setup logger --------------- # | |
class LevelFilter(logging.Filter): | |
def __init__(self, low, high=None): | |
if high is None: | |
high = low | |
self._low = low | |
self._high = high | |
logging.Filter.__init__(self) | |
def filter(self, record): | |
if self._low <= record.levelno <= self._high: | |
return True | |
return False | |
formatter = logging.Formatter( | |
'%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
# DEBUG through INFO goes to file | |
fh = logging.FileHandler('/tmp/debug.log') | |
fh.setFormatter(formatter) | |
fh.addFilter(LevelFilter(logging.DEBUG, logging.INFO)) | |
logger.addHandler(fh) | |
# WARNING or more go to stderr | |
sh = logging.StreamHandler(sys.stderr) | |
sh.setLevel(logging.WARN) | |
sh.setFormatter(formatter) | |
logger.addHandler(sh) | |
# ----------- Application code, use the logger --------------- # | |
logger.debug("This is debug...") | |
logger.info("This is information.") | |
logger.warn("This is a warning.") | |
logger.error("This is Error!") | |
logger.critical("This is CRITICAL") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment