Skip to content

Instantly share code, notes, and snippets.

@oscaromeu
Created January 11, 2022 09: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 oscaromeu/aeb7424cd4b65d182bbaae38b747afdd to your computer and use it in GitHub Desktop.
Save oscaromeu/aeb7424cd4b65d182bbaae38b747afdd to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import argparse
from ruamel.yaml import YAML
import logging.config
from pythonjsonlogger import jsonlogger
FORMAT = "[%(asctime)s %(levelname)-5s|%(name)s|%(filename)20s:%(lineno)-3s|%(funcName)20s()] %(message)s"
logger = logging.getLogger(__name__)
class Main:
""" might as well use a class. It'll make things easier later. """
def __init__(self, args=False):
""" init method, run at class creation """
self.args = args
def run(self):
""" do stuff here """
logger.info("info-level log message")
logger.debug("debug-level log message")
logger.error("error-level log message")
print("run.")
def read_yaml(file_path: str) -> dict:
yaml = YAML(typ='safe')
with open(file_path, 'r') as f:
return yaml.load(f)
def configure_logging(logging_config_file=None, verbose=False, log_file=None):
"""
The logs are configured from the configuration file in yaml.
If no configuration file is provided, a basic configuration is performed.
Likewise, if verbose is true, the default level of the logger is changed to DEBUG.
"""
if logging_config_file:
# noinspection PyBroadException
try:
logging_conf = read_yaml(logging_config_file)
except Exception:
print(f"Cannot read file {logging_config_file}. Configuring default logging")
else:
if log_file:
logging_conf['handlers']['file']['filename'] = log_file
logging.config.dictConfig(logging_conf)
if verbose:
level_by_config = logging.getLogger().getEffectiveLevel()
logging.getLogger().setLevel(min(level_by_config, logging.DEBUG))
return logging_conf
logging.basicConfig(filename=log_file, format=FORMAT,
level=logging.DEBUG if verbose else logging.INFO)
return None
def parse_args(argv):
"""
parse arguments/options
"""
p = argparse.ArgumentParser(description='App description')
p.add_argument('-v', '--verbose', dest='verbose', action='count', default=0,
help='verbose output. specify twice for debug-level output.')
p.add_argument("-c", "--config", action="store", dest="input_config_file",
help="Path to the configuration file.", default=None)
args = p.parse_args(argv)
return args
if __name__ == "__main__":
args = parse_args(sys.argv[1:])
configure_logging(args.input_config_file)
if args.verbose > 1:
logger.setLevel(logging.DEBUG)
elif args.verbose > 0:
logger.setLevel(logging.INFO)
main = Main(args)
main.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment