Created
October 28, 2015 21:51
-
-
Save MatthewRalston/fbc584dc9385a757a4d7 to your computer and use it in GitHub Desktop.
Python logging: configuration file and root_logger setup.
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
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() |
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
[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