Skip to content

Commit

Permalink
Update logging messages(#282) (#303)
Browse files Browse the repository at this point in the history
  • Loading branch information
FabioRosado authored and jacobtomlinson committed Oct 27, 2017
1 parent 1bae1a6 commit 31dffc2
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 80 deletions.
3 changes: 2 additions & 1 deletion opsdroid/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ def welcome_message(config):
"releases")
_LOGGER.info("=" * 40)
except KeyError:
pass
_LOGGER.warning("'welcome-message: true/false' is missing in "
"configuration.yaml")


def main():
Expand Down
19 changes: 9 additions & 10 deletions opsdroid/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ def __init__(self):
self.web_server = None
self.should_restart = False
self.stored_path = []
_LOGGER.info("Created main opsdroid object")

def __enter__(self):
"""Add self to existing instances."""
Expand Down Expand Up @@ -185,7 +184,7 @@ def start_databases(self, databases):
if isinstance(cls, type) and \
issubclass(cls, Database) and \
cls is not Database:
_LOGGER.debug("Adding database: " + name)
_LOGGER.debug("Adding database: %s", name)
database = cls(database_module["config"])
self.memory.databases.append(database)
self.eventloop.run_until_complete(database.connect(self))
Expand All @@ -195,43 +194,43 @@ async def parse(self, message):
self.stats["messages_parsed"] = self.stats["messages_parsed"] + 1
tasks = []
if message.text.strip() != "":
_LOGGER.debug("Parsing input: " + message.text)
_LOGGER.debug("Parsing input: %s", message.text)

tasks.append(
self.eventloop.create_task(parse_regex(self, message)))
tasks.append(
self.eventloop.create_task(parse_always(self, message)))

if "parsers" in self.config:
_LOGGER.debug("Processing parsers")
_LOGGER.debug("Processing parsers...")
parsers = self.config["parsers"]

dialogflow = [p for p in parsers if p["name"] == "dialogflow"]
_LOGGER.debug("Checking dialogflow")
_LOGGER.debug("Checking dialogflow...")
if len(dialogflow) == 1 and \
("enabled" not in dialogflow[0] or
dialogflow[0]["enabled"] is not False):
_LOGGER.debug("Parsing with Dialogflow")
_LOGGER.debug("Parsing with Dialogflow.")
tasks.append(
self.eventloop.create_task(
parse_dialogflow(self, message, dialogflow[0])))

luisai = [p for p in parsers if p["name"] == "luisai"]
_LOGGER.debug("Checking luisai")
_LOGGER.debug("Checking luisai...")
if len(luisai) == 1 and \
("enabled" not in luisai[0] or
luisai[0]["enabled"] is not False):
_LOGGER.debug("Parsing with luisai")
_LOGGER.debug("Parsing with luisai.")
tasks.append(
self.eventloop.create_task(
parse_luisai(self, message, luisai[0])))

witai = [p for p in parsers if p["name"] == "witai"]
_LOGGER.debug("Checking wit.ai")
_LOGGER.debug("Checking wit.ai...")
if len(witai) == 1 and \
("enabled" not in witai[0] or
witai[0]["enabled"] is not False):
_LOGGER.debug("Parsing with witai")
_LOGGER.debug("Parsing with witai.")
tasks.append(
self.eventloop.create_task(
parse_witai(self, message, witai[0])))
Expand Down
51 changes: 25 additions & 26 deletions opsdroid/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,35 +34,35 @@ def import_module(config):
try:
module = importlib.import_module(
config["module_path"] + "." + config["name"])
_LOGGER.debug("Loaded " + config["type"] + ": " +
_LOGGER.debug("Loaded %s: %s", config["type"],
config["module_path"])
return module

except ImportError as error:
_LOGGER.debug("Failed to load " + config["type"] +
" " + config["module_path"] + "." + config["name"])
_LOGGER.debug(error)
_LOGGER.debug("Failed to load %s.%s. ERROR: %s",
config["module_path"], config["name"], error)

try:
module = importlib.import_module(
config["module_path"])
_LOGGER.debug("Loaded " + config["type"] + ": " +
_LOGGER.debug("Loaded %s: %s", config["type"],
config["module_path"])
return module

except ImportError as error:
_LOGGER.debug("Failed to load " + config["type"] +
" " + config["module_path"])
_LOGGER.error("Failed to load %s: %s", config["type"],
config["module_path"])
_LOGGER.debug(error)

_LOGGER.error("Failed to load " + config["type"] +
" " + config["module_path"])
return None

@staticmethod
def check_cache(config):
"""Remove module if 'no-cache' set in config."""
if "no-cache" in config \
and config["no-cache"]:
_LOGGER.debug("'no-cache' set, removing " + config["install_path"])
_LOGGER.debug("'no-cache' set, removing %s",
config["install_path"])
if os.path.isdir(config["install_path"]):
shutil.rmtree(config["install_path"])
if os.path.isfile(config["install_path"] + ".py"):
Expand Down Expand Up @@ -127,8 +127,7 @@ def load_config_file(self, config_paths):
config_path = ""
for possible_path in config_paths:
if not os.path.isfile(possible_path):
_LOGGER.debug("Config file " + possible_path +
" not found")
_LOGGER.debug("Config file %s not found.", possible_path)
else:
config_path = possible_path
break
Expand Down Expand Up @@ -160,7 +159,7 @@ def include_constructor(loader, node):

try:
with open(config_path, 'r') as stream:
_LOGGER.info("Loaded config from %s", config_path)
_LOGGER.info("Loaded config from %s.", config_path)
return yaml.load(stream)
except yaml.YAMLError as error:
self.opsdroid.critical(error, 1)
Expand All @@ -184,7 +183,7 @@ def setup_modules_directory(self, config):

def load_modules_from_config(self, config):
"""Load all module types based on config."""
_LOGGER.debug("Loading modules from config")
_LOGGER.debug("Loading modules from config...")

self.setup_modules_directory(config)

Expand All @@ -193,7 +192,7 @@ def load_modules_from_config(self, config):
if 'databases' in config.keys() and config['databases']:
databases = self._load_modules('database', config['databases'])
else:
_LOGGER.warning("No databases in configuration")
_LOGGER.warning("No databases in configuration.")

if 'skills' in config.keys() and config['skills']:
skills = self._load_modules('skill', config['skills'])
Expand All @@ -214,7 +213,7 @@ def load_modules_from_config(self, config):

def _load_modules(self, modules_type, modules):
"""Install and load modules."""
_LOGGER.debug("Loading " + modules_type + " modules")
_LOGGER.debug("Loading %s modules...", modules_type)
loaded_modules = []

if not os.path.isdir(DEFAULT_MODULE_DEPS_PATH):
Expand Down Expand Up @@ -256,20 +255,20 @@ def _load_modules(self, modules_type, modules):
"config": config})
else:
_LOGGER.error(
"Module " + config["name"] + " failed to import")
"Module %s failed to import.", config["name"])

return loaded_modules

def _install_module(self, config):
# pylint: disable=R0201
"""Install a module."""
_LOGGER.debug("Installing " + config["name"])
_LOGGER.debug("Installing %s...", config["name"])

if os.path.isdir(config["install_path"]) or \
os.path.isfile(config["install_path"] + ".py"):
# TODO Allow for updating or reinstalling of modules
_LOGGER.debug("Module " + config["name"] +
" already installed, skipping")
_LOGGER.debug("Module %s already installed, skipping.",
config["name"])
return

if "path" in config:
Expand All @@ -278,12 +277,12 @@ def _install_module(self, config):
self._install_git_module(config)

if os.path.isdir(config["install_path"]):
_LOGGER.debug("Installed " + config["name"] +
" to " + config["install_path"])
_LOGGER.debug("Installed %s to %s", config["name"],
config["install_path"])
else:
_LOGGER.debug("Install of " + config["name"] + " failed")
_LOGGER.error("Install of %s failed.", config["name"])

# Install module dependancies
# Install module dependencies
if os.path.isfile(config["install_path"] + "/requirements.txt"):
self.pip_install_deps(config["install_path"] +
"/requirements.txt")
Expand All @@ -299,7 +298,7 @@ def _install_git_module(self, config):
if any(prefix in git_url for prefix in ["http", "https", "ssh"]):
# TODO Test if url or ssh path exists
# TODO Handle github authentication
_LOGGER.debug("Cloning from remote repository")
_LOGGER.info("Cloning from remote repository")
self.git_clone(git_url, config["install_path"],
config["branch"])
else:
Expand All @@ -308,7 +307,7 @@ def _install_git_module(self, config):
self.git_clone(git_url, config["install_path"],
config["branch"])
else:
_LOGGER.debug("Could not find local git repo " + git_url)
_LOGGER.error("Could not find local git repo %s", git_url)

@staticmethod
def _install_local_module(config):
Expand Down
8 changes: 4 additions & 4 deletions opsdroid/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def __init__(self):

async def get(self, key):
"""Get data object for a given key."""
_LOGGER.debug("Getting " + key + " from memory")
_LOGGER.debug("Getting %s from memory.", key)
database_result = await self._get_from_database(key)
if database_result is not None:
self.memory[key] = database_result
Expand All @@ -27,14 +27,14 @@ async def get(self, key):

async def put(self, key, data):
"""Put a data object to a given key."""
_LOGGER.debug("Putting " + key + " to memory")
_LOGGER.debug("Putting %s to memory", key)
self.memory[key] = data
await self._put_to_database(key, self.memory[key])

async def _get_from_database(self, key):
"""Get updates from databases for a given key."""
if not self.databases:
_LOGGER.warning("No databases configured, data will not persist")
_LOGGER.warning("No databases configured, data will not persist.")
return None

results = []
Expand All @@ -46,7 +46,7 @@ async def _get_from_database(self, key):
async def _put_to_database(self, key, data):
"""Put updates into databases for a given key."""
if not self.databases:
_LOGGER.warning("No databases configured, data will not persist")
_LOGGER.warning("No databases configured, data will not persist.")
else:
for database in self.databases:
await database.put(key, data)
15 changes: 8 additions & 7 deletions opsdroid/parsers/dialogflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async def call_dialogflow(message, config):
data=json.dumps(payload),
headers=headers)
result = await resp.json()
_LOGGER.debug("Dialogflow response - " + json.dumps(result))
_LOGGER.info("Dialogflow response - %s", json.dumps(result))

return result

Expand All @@ -45,8 +45,8 @@ async def parse_dialogflow(opsdroid, message, config):
return

if result["status"]["code"] >= 300:
_LOGGER.error("Dialogflow error - " +
str(result["status"]["code"]) + " " +
_LOGGER.error("Dialogflow error - %s - %s",
str(result["status"]["code"]),
result["status"]["errorType"])
return

Expand All @@ -70,12 +70,13 @@ async def parse_dialogflow(opsdroid, message, config):
try:
await skill["skill"](opsdroid, skill["config"],
message)

except Exception:
await message.respond(
"Whoops there has been an error")
await message.respond(
"Check the log for details")
_LOGGER.exception("Exception when parsing '" +
message.text +
"' against skill '" +
result["result"]["action"] + "'")
_LOGGER.exception("Exception when parsing '%s' "
"against skill '%s'.",
message.text,
result["result"]["action"])
14 changes: 6 additions & 8 deletions opsdroid/parsers/luisai.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async def call_luisai(message, config):
'&verbose=' + str(config['verbose']) +
'&q=' + message.text, headers=headers)
result = await resp.json()
_LOGGER.debug("luis.ai response - " + json.dumps(result))
_LOGGER.debug("luis.ai response - %s", json.dumps(result))

return result

Expand All @@ -46,9 +46,8 @@ async def parse_luisai(opsdroid, message, config):
# luis.ai responds with a status code
try:
if result["statusCode"] >= 300:
_LOGGER.error("luis.ai error - " +
str(result["statusCode"]) + " " +
result["message"])
_LOGGER.error("luis.ai error - %s %s",
str(result["statusCode"]), result["message"])
except KeyError:
pass

Expand All @@ -75,7 +74,6 @@ async def parse_luisai(opsdroid, message, config):
"Whoops there has been an error")
await message.respond(
"Check the log for details")
_LOGGER.exception("Exception when parsing '" +
message.text +
"' against skill '" +
result["query"] + "'")
_LOGGER.exception("Exception when parsing '%s' "
"against skill '%s'.",
message.text, result["query"])
8 changes: 4 additions & 4 deletions opsdroid/parsers/regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async def parse_regex(opsdroid, message):
"Whoops there has been an error")
await message.respond(
"Check the log for details")
_LOGGER.exception("Exception when parsing '" +
message.text +
"' against skill '" +
skill["regex"]["expression"] + "'")
_LOGGER.exception("Exception when parsing '%s' "
"against skill '%s'.",
message.text,
skill["regex"]["expression"])
16 changes: 7 additions & 9 deletions opsdroid/parsers/witai.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ async def call_witai(message, config):
resp = await session.get("https://api.wit.ai/message?v={}&q={}".format(
payload['v'], payload['q']), headers=headers)
result = await resp.json()
_LOGGER.debug("wit.ai response - " + json.dumps(result))
_LOGGER.info(result)
_LOGGER.info("wit.ai response - %s", json.dumps(result))
return result


Expand All @@ -40,8 +39,8 @@ async def parse_witai(opsdroid, message, config):
return

if 'code' in result:
_LOGGER.error("wit.ai error - " + str(result['code'])
+ " " + str(result['error']))
_LOGGER.error("wit.ai error - %s %s", str(result['code']),
str(result['error']))
return
elif result['entities'] == {}:
_LOGGER.error("wit.ai error - No intent found. Did you "
Expand All @@ -53,7 +52,7 @@ async def parse_witai(opsdroid, message, config):
except KeyError:
confidence = 0.0
if "min-score" in config and confidence < config['min-score']:
_LOGGER.debug("wit.ai score lower than min-score")
_LOGGER.info("wit.ai score lower than min-score")
return

if result:
Expand All @@ -73,7 +72,6 @@ async def parse_witai(opsdroid, message, config):
"Whoops there has been an error")
await message.respond(
"Check the log for details")
_LOGGER.exception("Exception when parsing '" +
message.text +
"' against skill '" +
parsed_skill + "'")
_LOGGER.exception("Exception when parsing %s "
"against skill %s'",
message.text, parsed_skill)
Loading

0 comments on commit 31dffc2

Please sign in to comment.