def config_file(self, value): """""" if value is False: self._CONFIG_FILE = False return # No change elif value == self.config_file: return # Something IS different _value = str(value).strip() err = "ConfigHandler.config_file.setter: Parameter 'config_file' must be in the format '/dir1/dir2/filename.conf'. (config_file='{V}')".format( V=_value) for p in ["void", "none", "false"]: if (len(_value) < 2 or re.match("^{p}$".format(p=p), _value, re.IGNORECASE)): self._CONFIG_FILE = False log.debug( "ConfigHandler.config_file.setter: config_file set to 'False'." ) return # Check config file exists if not checks.isFile( _value): #, full = True, relative = False, trailing = False): raise ValueError( "config_file '{F}' does not appear to exist or is not readable. {E}" .format(F=_value, E=err)) # Set self._CONFIG_FILE = _value # Load it by default. No time like the present self._load_all_from_config_file() return
def __init__( self, config_file=False, # Param so it can be passed in blind *args, **kwargs): """""" # Call here to start logging with whats in kwargs # DO PASS IN KWARGS here self.override_log(kwargs) # Actually creates the loghandler object. log.debug('Initiating logger with {K}'.format(K=str(kwargs)), **kwargs) log.info( "ConfigHandler called with '{F}'".format(F=str(self.config_file))) # self.override_log(**kwargs) # Singleton. If confighandler object exists, do not re-run __init__, if self.__exists: # this will defacto Re-run the config file if kwargs.pop('reload', False): self.config_file = self._CONFIG_FILE # __init__get run everytime even if singletone. So if exists, return return # **kwargs here passes in loghandler parameers from ConfigHandler instantiation try: self.callobj = inspect.stack()[1][0].f_locals['self'] self.caller_name = sys._current_frames().values()[0] self.caller_name = self.caller_name.f_back.f_globals['__file__'] self.caller_name = os.path.basename(self.caller_name) self.caller_name = self.caller_name.lower().replace('.py', '') except KeyError as e: log.debug( "ConfigHandler was instantiated by a non-class-object. Creating empty placeholder object" ) self.callobj = Callobj() self.caller_name = 'UNKNOWN_CALLER' # DEFAULT PARAMETERS ARE SET HERE # This defacto loads the config file self.config_file = config_file # log.info("Using config_file: '" + str(self.config_file) + "'.") # self._load_all_from_config_file() # else: # log.info("NO CONFIG FILE LOADED. CREATING BLANK OBJECT. ('config_file' = False).") # Now that we have parsed the config file, use any logging params from the config file # DO NOT PASS KWARGS to use settings loaded from config_file!!! self.override_log()
def override_log(self, *args, **kwargs): """ This overrides any parameters in the existing LogHandler object The logic is: - If the ConfigHandler object has a log attribute, it was picked up from the config_file, so should override whats in there. - Any kwargs passed in should override the stuff in the ConfigHandler object. - If there's no ConfigHandler object attribute AND no kwarg passed in, setting 'UNCHANGED' will be passed to the log object...meaning ignore the variable. """ # List of log params # _params = ["app_name", "logfile", "log_level", "screendump", "format", "create_paths", "migrate"] # Holder for updated log parameters # _log = '' _log_kwargs = {} # These are the LogHandler object params for _param in [ "app_name", "logfile", "log_level", "screendump", "format", "create_paths", "migrate" ]: # Set the log param to the existing log param, if it exists. try: _value = kwargs.pop(_param, False) # Always returns value # Set _log_kwargs[_param] to passed in value, or the existing config object parameter if _value: _log_kwargs[_param] = _value # Passed to log call vars( )[_param] = _value # Sets to local configHandler object # KeyError if no self.vars()[_param].Pass except KeyError: pass # _log_kwargs[_param] = 'UNCHANGED' # Now that _log_kwargs is loaded with ONLY pertinent params, ### THE CALL TO LOG.DEBUG IS WHAT ACTUALLY RESETS THE PARAMETERS ###### if len(_log_kwargs) > 0: # No params to change log.debug( "Resetting the following log parameters: {P}".format( P=str(_log_kwargs)), **_log_kwargs)
def load(self, config_file, *args, **kwargs): log.debug( "ConfigHandler.load: Loading '{F}'".format(F=str(config_file))) self.config_file = config_file
except ValueError: pass # if (re.match("^[0-9]+\.[0-9]*$", value)): return float(value) # if (re.match("^[0-9]+$", value)): return int(value) # Check for list and dict if (value.startswith('[') or value.startswith('{')): return ast.literal_eval(value) # Otherwise just return original string, no conversion return value if __name__ == "__main__": # import time log.debug( "Starting CUPS-QRNote-backend", app_name="QRNote", logfile="syslog", log_level=10, screendump=True, # formatter = '%(asctime)s-%(name)s-%(levelname)s-%(message)s', create_paths=True) # o = ConfigHandler("/Users/mikes/Documents/Eclipseworkspace/Bioproximity/OpenMS-Python-Luigi/site-packages/Bioproximity/etc/Workflow.conf") o = ConfigHandler(None) print o.config_file print o.AWS_ID #=========================================================================== # o.var1 = 'test' # print o.var1 # time.sleep(.5) # print o.var2 #=========================================================================== #===============================================================================