Skip to content

Instantly share code, notes, and snippets.

@mikeblum
Last active October 4, 2016 22:24
Show Gist options
  • Save mikeblum/ea0a9e3befd1281fa0fb230ef64700b5 to your computer and use it in GitHub Desktop.
Save mikeblum/ea0a9e3befd1281fa0fb230ef64700b5 to your computer and use it in GitHub Desktop.
My goto Python logging template - lints 10/10 in pylint
#!/usr/bin/env python
"""
Global Python log configuration settings
@author mblum
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import logging
import os
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
LOG_FORMAT = '%(asctime)s %(name)s:%(levelname)-8s %(message)s'
LOG_DATE_FORMAT = '%a, %d %b %Y %H:%M:%S'
def instantiate_logger(name):
"""
Instantiate a global named logger
Configure OS variables for logfile and level
LOG_FILE - defaults to temp.log in the working directory
LOG_LEVEL - defaults to DEBUG
Find configuration details here:
https://docs.python.org/2/howto/logging-cookbook.html
"""
log_file = None
log_level = None
try:
log_file = os.environ['LOG_FILE']
except KeyError as exp:
print('LOG_FILE OS variable not configured {}'.format(str(exp)))
if log_file is None:
log_file = 'temp.log'
try:
log_level = os.environ['LOG_LEVEL']
except KeyError as exp:
print('LOG_LEVEL OS variable not configured {}'.format(str(exp)))
if log_level is None:
log_level = 'debug'
if log_level not in LEVELS:
print('log level not specified - falling back to debug')
log_level = 'debug'
logging.basicConfig(filename=log_file,
level=LEVELS[log_level],
format=LOG_FORMAT,
datefmt=LOG_DATE_FORMAT)
print('configuring logging: {level} to {log}'.format(level=log_level,
log=log_file))
logger = logging.getLogger(name)
logger.info('Logger ready...')
return logger
if __name__ == '__main__':
instantiate_logger('main')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment