Skip to content

Instantly share code, notes, and snippets.

@jesserobertson
Created June 13, 2018 03:37
Show Gist options
  • Save jesserobertson/7abfa074f1f1b60208fa96896dbcfaac to your computer and use it in GitHub Desktop.
Save jesserobertson/7abfa074f1f1b60208fa96896dbcfaac to your computer and use it in GitHub Desktop.
Enable logging to a Jupiter notebook by module namespace
import logging, sys
def log_to_notebook(module=None, level='INFO'):
"""
Sets up logging to stdout so we can capture it in the notebook
Parameters:
module - the module to log from. To log only certain submodules
do something like `module='placer.stream'`. If None, default is
to get the root logger which logs everything.
level - the level to log at. Optional, defaults to `INFO`.
"""
# Find whether we're getting a module name or not
if module is not None:
logger = logging.getLogger(module)
else:
logger = logging.getLogger()
# Lookup log level
level = getattr(logging, level)
# Set up logger
logger.setLevel(level)
channel = logging.StreamHandler(sys.stdout)
channel.setLevel(level)
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
channel.setFormatter(formatter)
logger.addHandler(channel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment