Created
August 29, 2014 04:18
-
-
Save omwah/6746b59309cee0e136ff to your computer and use it in GitHub Desktop.
Handy Python logging initialization function that sets up logging to screen and to a file
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
def init_logging(verbose=False, log_file=None): | |
logger = logging.getLogger() | |
logger.setLevel(logging.DEBUG) | |
if verbose: | |
level = logging.DEBUG | |
else: | |
level = logging.INFO | |
# Start up console handler | |
console = logging.StreamHandler() | |
console.setLevel(level) | |
console.setFormatter(logging.Formatter(fmt=SCREEN_FORMAT)) | |
logger.addHandler(console) | |
# Log to a file if the option is supplied | |
if log_file: | |
log_dir = os.path.dirname(log_file) | |
if len(log_dir) > 0 and not os.path.exists(log_dir): | |
os.makedirs(os.path.dirname(log_file)) | |
logger = logging.getLogger() | |
fileout = logging.FileHandler(log_file, "w") | |
fileout.setLevel(logging.DEBUG) | |
fileout.setFormatter(logging.Formatter(fmt=LOG_FORMAT)) | |
logger.addHandler(fileout) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment