def init(): ''' Set up logging and load configuration data. This is intended for use by scripts and is intended to remove boilerplate code. Typically a script will require a log file (or directory) and a config (or properties) file to be passed as command line options. `init` will look for any of the following in `KWARGS` (keyword arguments): * logdir * logfile * config * configspec ''' global KWARGS if CONFIGSPECKEY in KWARGS: configspec = configobj.ConfigObj(StringIO(KWARGS[CONFIGSPECKEY]), list_values=False) else: configspec = None configfile = KWARGS.get(CONFIGKEY, None) if configfile is not None: #isinstance check to see if a file name has been passed #necessary because the caller is free to pass something else #suitable for creating a ConfigObj, eg. a list of strings if isinstance(configfile, basestring) and not exists(configfile): raise OSError('Config file doesn\'t exist: %s' % configfile) else: config = configobj.ConfigObj(configfile, configspec=configspec, write_empty_values=True) if configspec is not None: from itsalib.util.validate import Validator vdt = Validator() result = config.validate(vdt) if result is not True: msg = 'Validation Errors.\n\n' for item in configobj.flatten_errors(config, result): msg += ' %s:%s:%s\n' % item msg += '\n%s\n' % configspec sys.exit(msg) #replace the configkey value with an actual instance of a configobj KWARGS[CONFIGKEY] = config logfile = logstart(KWARGS.get(LOGDIRKEY, None), KWARGS.get(LOGFILEKEY, None), KWARGS.get(LOGFILEPREFIXKEY, '')) KWARGS[LOGFILEKEY] = logfile if hasattr(CALLER, '__file__'): calling_script = abspath(CALLER.__file__) log.info("SCRIPT: '%s'" % calling_script) if configfile and config.filename: log.info("CONFIGURATION file: '%s'" % abspath(config.filename)) for i,arg in enumerate(ARGS): log.info("arg%s = %s" % (i,arg)) for key, val in KWARGS.iteritems(): if not key.startswith('config'): log.info("%s = %s" % (key, val)) log.divider() return logfile
def logstart(logfile=None, logdir=None): ''' Initialise file and console loggers. * logdir: The directory where the timestamped log file will be saved. * logfile: If `logdir` is not specified, log to this file. :return: The log file path. ''' logfile = log.start(logfile, logdir) log.divider() if logfile: log.info("Started logger. Logging to file: '%s'" % logfile) else: log.info("Started logger. A log file or log directory was not specified.") return logfile