Created
October 11, 2016 22:41
-
-
Save rldotai/ade89c0b23ddd78d08b9d6cccb116dd8 to your computer and use it in GitHub Desktop.
Quick logging setup
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
""" | |
A quick logging setup and some helper functions. | |
Some code taken from: http://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/ | |
""" | |
import logging | |
# get a logger, set the logging level | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
# set up formatter | |
# formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | |
formatter = logging.Formatter('%(asctime)s - %(message)s') | |
# log to stream | |
handler = logging.StreamHandler() | |
handler.setLevel(logging.DEBUG) | |
handler.setFormatter(formatter) | |
logger.addHandler(handler) | |
# log to file | |
# fh = logging.FileHandler('log_filename.txt') | |
# fh.setLevel(logging.DEBUG) | |
# fh.setFormatter(formatter) | |
# logger.addHandler(fh) | |
def log_dict(dct, level=logging.INFO, logger=logging.getLogger()): | |
"""Log dictionaries with nicely aligned columns.""" | |
longest = max([len(str(x)) for x in dct.keys()]) | |
for key in sorted(dct.keys(), key=lambda x: str(x)): | |
format_string = '{0:%d}: {1}'%longest | |
netlog.log(level, format_string.format(key, dct[key])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment