Source code for ase.logging
"""Utility functions for configuring logging.
Copyright (c) 2015-2018, Garth Zeglin. All rights reserved. Licensed under the terms
of the BSD 3-clause license.
.. moduleauthor:: Garth Zeglin <garthz@cmu.edu>
"""
# Enable basic compatibility features to work with either Python 2 or 3.
from __future__ import print_function, absolute_import, unicode_literals
# Standard library modules.
import logging
################################################################
[docs]def create_script_logger(scriptname, args):
"""Create a top-level logger and a list of logging handlers specified by conventional command-line arguments.
:param args: a Namespace returned by argparse
:return: (logger, handlers) - a top-level logger and a list of handlers to add to other loggers
"""
handlers = list()
# Open a log file for detailed logging.
if args.log is not None:
file_handler = logging.FileHandler(args.log)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S"))
handlers.append(file_handler)
# Open a console log stream.
if not args.quiet:
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG if args.debug else logging.INFO if args.verbose else logging.WARNING)
console_handler.setFormatter(logging.Formatter('%(levelname)s:%(name)s: %(message)s'))
handlers.append(console_handler)
# If no outputs are specified, provide a null handler.
if len(handlers) == 0:
handlers.append(logging.NullHandler())
# Configure the handlers for the root logger, to be used by all subsidiary loggers.
root_logger = logging.getLogger()
for h in handlers:
root_logger.addHandler(h)
# Create a top-level script logger.
logger = logging.getLogger(scriptname)
logger.setLevel(logging.DEBUG)
return logger, handlers
################################################################
[docs]def add_logging_arguments(parser):
"""Add default logging control arguments to an argparse parser."""
parser.add_argument('--verbose', action='store_true', help='Enable informational logging to console.' )
parser.add_argument('--debug', action='store_true', help='Enable debugging logging to console. Supersedes verbose.' )
parser.add_argument('--quiet', action='store_true', help='Suppress all logging to console.' )
parser.add_argument('--log', help='Optional log file path with detailed output.')
return
################################################################