Skip to content

Instantly share code, notes, and snippets.

@MatthewRalston
Created October 28, 2015 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewRalston/fbc584dc9385a757a4d7 to your computer and use it in GitHub Desktop.
Save MatthewRalston/fbc584dc9385a757a4d7 to your computer and use it in GitHub Desktop.
Python logging: configuration file and root_logger setup.
import logging
import logging.config
def get_root_logger(loglevel, logfile=None, log_config="log.conf"):
# Requires 'import logging' and 'import logging.config'
def log_level(loglevel):
case = {"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR}
return case[loglevel.upper()]
logging.config.fileConfig(log_config)
root_logger = logging.getLogger()
log_format = root_logger.handlers[0].format
for handler in root_logger.handlers:
handler.setLevel(log_level(loglevel)) # Change the loglevel for the default (Console) level logger
if logfile: # If a logfile is specified, add as a handler for VERBOSE/DEBUG output and set to default format
file_handler = logging.FileHandler(logfile,mode="a")
file_handler.setLevel(logging.DEBUG)
file_handler.format = log_format
root_logger.addHandler(file_handler)
return root_logger
if __name__ == '__main__':
# Parse Command-Line Arguments
parser = argparse.ArgumentParser()
parser.add_argument('--option1', help="Option", default="something")
parser.add_argument('mandatory', help="Mandatory argument")
parser.add_argument('--log-level', help="Prints warnings to console by default",default="WARNING",choices=["DEBUG","INFO","WARNING","ERROR"])
parser.add_argument('--log-file', help="Print log to file.", default="/somewhere/logconf.log")
args = parser.parse_args()
# Set up the logger
root_logger = get_root_logger(args.log_level,logfile=args.log_file)
# Do work
main()
[loggers]
keys=root
[handlers]
keys=console
[formatters]
keys=complex
[logger_root]
level=DEBUG
handlers=console
[handler_console]
class=StreamHandler
level=WARNING
formatter=complex
args=(sys.stderr,)
[formatter_complex]
format=%(levelname)s: %(asctime)s || %(name)s %(module)s %(funcName)sL%(lineno)s: %(message)s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment