Skip to content

Instantly share code, notes, and snippets.

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 ltfschoen/52de119b32d14b62e14a6746a32476bf to your computer and use it in GitHub Desktop.
Save ltfschoen/52de119b32d14b62e14a6746a32476bf to your computer and use it in GitHub Desktop.
main_function_that_takes_debug_level_from_cli_in_python.py
#!/usr/bin/env python
import sys
import logging
import logging.config # import associated logging.conf. Refer to https://docs.python.org/3/howto/logging.html
import solution # import a file called say solution.py
def get_log_level(log_args):
valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR'] # numeric levels 10, 20, 30, 40
proposed_level = log_args[0].split("=", 1)[1].upper()
if not proposed_level in valid_levels:
raise ValueError('Invalid log level: %s' % proposed_level)
return proposed_level
def main():
"""
Note: Manually override the lowest-severity log message level
that the logger will handle from the command line by executing with flags:
i.e. python main.py --log=WARNING
Sample usage:
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
"""
# Load logger config
logging.config.fileConfig('logging.conf')
# Create logger
logger = logging.getLogger('sudoku logger')
logger.setLevel('ERROR') # specifies lowest-severity log message a logger will handle
if len(sys.argv):
log_args = [arg for arg in sys.argv if '--log=' in arg]
if len(log_args) > 0:
logger.setLevel(get_log_level(log_args))
# Get current logging level
numeric_level = logging.getLogger().getEffectiveLevel()
# Note: Logging to file is not working
# logging.basicConfig(filename='logger.log', level=numeric_level) # filemode='w',
logging.info('Starting Sudoku')
solution.run()
logging.info('Finished Sudoku')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment