Skip to content

Instantly share code, notes, and snippets.

@theTonyHo
Last active August 29, 2015 14:03
Show Gist options
  • Save theTonyHo/1ca70c83965705ea69ba to your computer and use it in GitHub Desktop.
Save theTonyHo/1ca70c83965705ea69ba to your computer and use it in GitHub Desktop.
Logging function to set up and create a logging object.
import logging
import os
def Logger(loggerName, fileName=None, console=False):
"""
Instantiate a logger object with default Formatter.
Default level is set to DEBUG (Show all messages)
Args:
loggerName: Name of the logger. Usually __file__ or something sensible.
fileName: File name of the log file. If ommitted, logger will default to console
console: Display in console. Only effective when filename is specified.
Returns:
Logger Object
Reference: http://stackoverflow.com/questions/13733552/logger-configuration-to-log-to-file-and-print-to-stdout
"""
# Set up formatter
logFormatter = logging.Formatter("%(asctime)s [%(module)s] [%(threadName)-12.12s] [%(levelname)-5.4s] : %(message)s")
# Create Logger object
logger = logging.getLogger(loggerName)
# Set default level
logger.setLevel(logging.DEBUG)
if fileName:
# Add File Handler to logger if fileName is specified
logFileName = fileName
fileExtAllowed = [".txt", ".log"]
# Split file and extension
fileNameWithoutExt, fileExt = os.path.splitext(fileName)
# Add .log extension if target file does not have the allowed extension
if not fileExt in fileExtAllowed:
logFileName = fileName + ".log"
fileHandler = logging.FileHandler(logFileName)
fileHandler.setFormatter(logFormatter)
logger.addHandler(fileHandler)
print "Logging started => {}".format(logFileName)
else:
#This is to ensure that logging has at least one Handler.
console = True
if console:
# Add
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
logger.addHandler(consoleHandler)
return logger
if __name__ == "__main__":
# Uncomment the different example to test.
# Example 1 - Console
logger = Logger("LOG")
# # Example 2 - File
# logger = Logger("LOG", __file__)
# # Example 3 - File and Console
# logger = Logger("LOG", __file__, True)
# Re-set logger level.
# Refer to hierarchy table at https://docs.python.org/2/library/logging.html#logging-levels
logger.setLevel(logging.DEBUG)
logger.critical("MY CRITICAL MESSAGE")
logger.error("MY ERROR MESSAGE")
logger.warning("MY WARNING MESSAGE")
logger.info("MY INFO MESSAGE")
logger.debug("MY DEBUG MESSAGE")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment