Created
June 13, 2018 03:37
-
-
Save jesserobertson/7abfa074f1f1b60208fa96896dbcfaac to your computer and use it in GitHub Desktop.
Enable logging to a Jupiter notebook by module namespace
This file contains hidden or 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, 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