Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Created April 8, 2017 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perrygeo/b8774cbe739141fc8f276e9cd7775155 to your computer and use it in GitHub Desktop.
Save perrygeo/b8774cbe739141fc8f276e9cd7775155 to your computer and use it in GitHub Desktop.
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