def init(cls): """ Initializes the class, sets the default log level and creates the required handlers. """ # Check configs manually, the Mycroft configuration system can't be # used since it uses the LOG system and would cause horrible cyclic # dependencies. confs = [SYSTEM_CONFIG, USER_CONFIG] config = {} for conf in confs: try: merge_dict(config, load_commented_json(conf) if isfile(conf) else {}) except Exception as e: print('couldn\'t load {}: {}'.format(conf, str(e))) cls.level = logging.getLevelName(config.get('log_level', 'INFO')) log_message_format = ( '{asctime} | {levelname:8} | {process:5} | {name} | {message}') formatter = logging.Formatter(log_message_format, style='{') formatter.default_msec_format = '%s.%03d' cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) # Enable logging in external modules cls.create_logger('').setLevel(cls.level)
def __load(config, location): if exists(location) and isfile(location): try: config.update(load_commented_json(location)) LOG.debug("Configuration '%s' loaded" % location) except Exception, e: LOG.error("Error loading configuration '%s'" % location) LOG.error(repr(e))
def test_load(self): # Load normal JSON file with open('plain.json', 'rw') as f: data_from_plain = json.load(f) # Load commented JSON file data_from_commented = load_commented_json('commented.json') # Should be the same... self.assertEqual(data_from_commented, data_from_plain)
def save(config, is_system=False): """ Save configuration ``config``. """ ConfigurationManager.update(config) location = SYSTEM_CONFIG if is_system else USER_CONFIG loc_config = load_commented_json(location) with open(location, 'w') as f: config = loc_config.update(config) json.dump(config, f)
def save(config, is_system=False): """ Save configuration ``config``. """ ConfigurationManager.update(config) location = SYSTEM_CONFIG if is_system else USER_CONFIG loc_config = load_commented_json(location) with open(location, 'w') as f: config = loc_config.update(config) json.dump(config, f)
def test_load(self): # Load normal JSON file with open('plain.json', 'rw') as f: data_from_plain = json.load(f) # Load commented JSON file data_from_commented = load_commented_json('commented.json') # Should be the same... self.assertEqual(data_from_commented, data_from_plain)
def __init__(self, cache=None): super().__init__(None) cache = cache or WEB_CONFIG_CACHE from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi from mycroft.api import is_backend_disabled if is_backend_disabled(): # disable options that require backend config = { "server": { "metrics": False, "sync_skill_settings": False }, "skills": {"upload_skill_manifest": False}, "opt_in": False } for key in config: self.__setitem__(key, config[key]) else: api = DeviceApi() setting = api.get_settings() location = None try: location = api.get_location() except RequestException as e: LOG.error("RequestException fetching remote location: {}" .format(str(e))) if exists(cache) and isfile(cache): location = load_commented_json(cache).get('location') if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error("RequestException fetching remote configuration: {}" .format(str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache)
def init(cls): sys_config = '/etc/mycroft/mycroft.conf' config = load_commented_json(sys_config) if isfile(sys_config) else {} cls.level = logging.getLevelName(config.get('log_level', 'DEBUG')) fmt = '%(asctime)s.%(msecs)03d - ' \ '%(name)s - %(levelname)s - %(message)s' datefmt = '%H:%M:%S' formatter = logging.Formatter(fmt, datefmt) cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) cls.create_logger('') # Enables logging in external modules
def test_load(self): root_dir = dirname(__file__) # Load normal JSON file plainfile = join(root_dir, 'plain.json') with open(plainfile, 'rw') as f: data_from_plain = json.load(f) # Load commented JSON file commentedfile = join(root_dir, 'commented.json') data_from_commented = load_commented_json(commentedfile) # Should be the same... self.assertEqual(data_from_commented, data_from_plain)
def test_load(self): root_dir = dirname(__file__) # Load normal JSON file plainfile = join(root_dir, 'plain.json') with open(plainfile, 'rw') as f: data_from_plain = json.load(f) # Load commented JSON file commentedfile = join(root_dir, 'commented.json') data_from_commented = load_commented_json(commentedfile) # Should be the same... self.assertEqual(data_from_commented, data_from_plain)
def save(config, is_system=False): """ Save configuration ``config``. """ ConfigurationManager.update(config) location = SYSTEM_CONFIG if is_system else USER_CONFIG try: LOG.info("Saving config") loc_config = load_commented_json(location) with open(location, 'w') as f: ConfigurationLoader.merge_conf(loc_config, config) json.dump(loc_config, f) except Exception as e: LOG.error(e)
def init(cls): confs = [SYSTEM_CONFIG, USER_CONFIG] config = {} for conf in confs: merge_dict(config, load_commented_json(conf) if isfile(conf) else {}) cls.level = logging.getLevelName(config.get('log_level', 'DEBUG')) fmt = '%(asctime)s.%(msecs)03d - ' \ '%(name)s - %(levelname)s - %(message)s' datefmt = '%H:%M:%S' formatter = logging.Formatter(fmt, datefmt) cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) cls.create_logger('') # Enables logging in external modules
def load_local(self, path): """ Load local json file into self. Args: path (str): file to load """ if exists(path) and isfile(path): try: config = load_commented_json(path) for key in config: self.__setitem__(key, config[key]) LOG.debug("Configuration {} loaded".format(path)) except Exception, e: LOG.error("Error loading configuration '{}'".format(path)) LOG.error(repr(e))
def load_local(self, path): """ Load local json file into self. Args: path (str): file to load """ if exists(path) and isfile(path): try: config = load_commented_json(path) for key in config: self.__setitem__(key, config[key]) LOG.debug("Configuration {} loaded".format(path)) except Exception, e: LOG.error("Error loading configuration '{}'".format(path)) LOG.error(repr(e))
def __init__(self, cache=None): super(RemoteConf, self).__init__(None) cache = cache or join(xdg.BaseDirectory.xdg_cache_home, 'mycroft', 'web_cache.json') from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi api = DeviceApi() setting = api.get_settings() location = None try: location = api.get_location() except RequestException as e: LOG.error( "RequestException fetching remote location: {}".format( str(e))) if exists(cache) and isfile(cache): location = load_commented_json(cache).get('location') if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error( "RequestException fetching remote configuration: {}".format( str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache)
def init(cls): confs = [SYSTEM_CONFIG, USER_CONFIG] config = {} for conf in confs: try: merge_dict(config, load_commented_json(conf) if isfile(conf) else {}) except Exception as e: print('couldn\'t load {}: {}'.format(conf, str(e))) cls.level = logging.getLevelName(config.get('log_level', 'INFO')) fmt = '%(asctime)s.%(msecs)03d - ' \ '%(name)s - %(levelname)s - %(message)s' datefmt = '%H:%M:%S' formatter = logging.Formatter(fmt, datefmt) cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) # Enable logging in external modules cls.create_logger('').setLevel(cls.level)
def __init__(self, cache=None): super(RemoteConf, self).__init__(None) cache = cache or WEB_CONFIG_CACHE from mycroft.api import is_paired if not is_paired(): self.load_local(cache) return try: # Here to avoid cyclic import from mycroft.api import DeviceApi api = DeviceApi() setting = api.get_settings() try: location = api.get_location() except RequestException as e: LOG.error("RequestException fetching remote location: {}" .format(str(e))) if exists(cache) and isfile(cache): location = load_commented_json(cache).get('location') if location: setting["location"] = location # Remove server specific entries config = {} translate_remote(config, setting) for key in config: self.__setitem__(key, config[key]) self.store(cache) except RequestException as e: LOG.error("RequestException fetching remote configuration: {}" .format(str(e))) self.load_local(cache) except Exception as e: LOG.error("Failed to fetch remote configuration: %s" % repr(e), exc_info=True) self.load_local(cache)
def init(cls): sys_config = '/etc/mycroft/mycroft.conf' config = load_commented_json(sys_config) if isfile(sys_config) else {} cls.level = logging.getLevelName(config.get('log_level', 'DEBUG')) fmt = '%(asctime)s.%(msecs)03d - ' \ '%(name)s - %(levelname)s - %(message)s' datefmt = '%H:%M:%S' formatter = logging.Formatter(fmt, datefmt) cls.handler = logging.StreamHandler(sys.stdout) cls.handler.setFormatter(formatter) cls.create_logger('') # Enables logging in external modules def make_method(fn): @classmethod def method(cls, *args, **kwargs): cls._log(fn, *args, **kwargs) method.__func__.__doc__ = fn.__doc__ return method # Copy actual logging methods from logging.Logger for name in ['debug', 'info', 'warning', 'error', 'exception']: setattr(cls, name, make_method(getattr(logging.Logger, name)))
# You should have received a copy of the GNU General Public License # along with Mycroft Core. If not, see <http://www.gnu.org/licenses/>. import json import logging from os.path import isfile from mycroft.util.json_helper import load_commented_json SYSTEM_CONFIG = '/etc/mycroft/mycroft.conf' __author__ = 'seanfitz' log_level = "DEBUG" if isfile(SYSTEM_CONFIG): config = load_commented_json(SYSTEM_CONFIG) log_level = config.get("log_level", "DEBUG") FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=FORMAT, level=logging.getLevelName(log_level)) logger = logging.getLogger("MYCROFT") def getLogger(name="MYCROFT"): """ Get a python logger :param name: Module name for the logger :return: an instance of logging.Logger """