Created
September 3, 2013 19:02
-
-
Save 9b/6428140 to your computer and use it in GitHub Desktop.
Logging for fun!
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
loggersS = set() | |
def logger(loggerName, level, logFile=None): | |
''' | |
Get a logging instance | |
@param loggerName name of the logging instance | |
@param level level in which to log | |
@param logFile the absolute path to the log file to use. you must have write perms for this! | |
@return logging object used for later on | |
''' | |
# do we already have a logger for this? | |
if loggerName in loggersS: | |
# we do, so we can just return the logger singleton for this name | |
return logging.getLogger(loggerName) | |
else: | |
# we do not; we need to get the logger singleton for this name for the first time and set it up | |
logger = logging.getLogger(loggerName) | |
loggersS.add(loggerName) | |
# Set the log level | |
if level == "INFO": | |
logger.setLevel(logging.INFO) | |
elif level == "WARN": | |
logger.setLevel(logging.WARN) | |
elif level == "DEBUG": | |
logger.setLevel(logging.DEBUG) | |
elif level == "ERROR": | |
logger.setLevel(logging.ERROR) | |
else: | |
pass | |
# Some formatters. Note that the fmtrNoColor is only used when logging to a file | |
fmtr = logging.Formatter('\033[36m%(levelname)-5s %(module)s:%(funcName)s():%(lineno)d %(asctime)s\033[0m| %(message)s') | |
fmtrNoColor = logging.Formatter('%(levelname)-5s %(module)s:%(funcName)s():%(lineno)d %(asctime)s | %(message)s') | |
# The streamhandler is always present | |
shandler = logging.StreamHandler(sys.stdout) | |
shandler.setFormatter(fmtr) | |
logger.addHandler(shandler) | |
# the file logger is optional | |
if logFile is not None: | |
if not os.path.exists(os.path.dirname(logFile)): | |
logger.warn("cannot log to logFile=%s: the base directory %s does not exist" % (logFile, os.path.dirname(logFile))) | |
elif not os.access(os.path.dirname(logFile), os.W_OK): | |
# yes, i know the risk in using access()--I just don't care | |
logger.warn("cannot log to logFile=%s: cannot write to indicated file due to incorrect permissions" % logFile) | |
else: | |
fhandler = handlers.WatchedFileHandler(logFile) | |
fhandler.setFormatter(fmtrNoColor) | |
logger.info("logging to %s in addition to stdout" % logFile) | |
logger.addHandler(fhandler) | |
return logger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment