Skip to content

Commit

Permalink
Merge pull request #16 from thin-edge/logging
Browse files Browse the repository at this point in the history
Replace all prints with logging
  • Loading branch information
reubenmiller authored Sep 17, 2024
2 parents 9ff4b65 + 24bcee8 commit 7a27c77
Showing 1 changed file with 21 additions and 19 deletions.
40 changes: 21 additions & 19 deletions gittyup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import json
import os
import time
import logging
import tomllib
import sys
from pathlib import Path
Expand All @@ -14,7 +15,6 @@
CLONE_DIR = "repo"
CHECK_INTERVAL = 15


class GittyUpClient:
"""GittyUp client
Expand All @@ -30,7 +30,7 @@ def __init__(self):
def connect(self):
"""Connect to the thin-edge.io MQTT broker"""
if self.client is not None:
print(f"MQTT client already exists. connected={self.client.is_connected()}")
logger.info(f"MQTT client already exists. connected={self.client.is_connected()}")
return

# Don't use a clean session so no messages will go missing
Expand All @@ -42,7 +42,7 @@ def connect(self):
client.on_message = self.on_message
client.on_subscribe = self.on_subscribe

print(f"Trying to connect to the MQTT broker: host=localhost:1883")
logger.debug(f"Trying to connect to the MQTT broker: host=localhost:1883")

client.will_set(
"te/device/main/service/gittyup/status/health",
Expand All @@ -65,7 +65,7 @@ def shutdown(self):
def subscribe(self):
"""Subscribe to thin-edge.io device profile topic."""
self.client.subscribe(self.sub_topic)
print(f"subscribed to topic {self.sub_topic}")
logger.debug(f"subscribed to topic {self.sub_topic}")

def loop_forever(self):
"""Block infinitely"""
Expand All @@ -78,11 +78,11 @@ def publish_tedge_command(self, topic, payload):

def on_connect(self, client, userdata, flags, reason_code):
if reason_code != 0:
print(
logger.error(
f"Failed to connect. result_code={reason_code}. Retrying the connection"
)
else:
print(f"Connected to MQTT broker! result_code={reason_code}")
logger.info(f"Connected to MQTT broker! result_code={reason_code}")
client.publish(
"te/device/main/service/gittyup/status/health",
json.dumps({"status": "up"}),
Expand All @@ -92,7 +92,7 @@ def on_connect(self, client, userdata, flags, reason_code):
self.subscribe()

def on_disconnect(self, client, userdata, reason_code):
print(f"Client was disconnected: result_code={reason_code}")
logger.info(f"Client was disconnected: result_code={reason_code}")

def on_message(self, client, userdata, message):
payload_dict = json.loads(message.payload)
Expand All @@ -104,7 +104,7 @@ def on_subscribe(self, client, userdata, mid, granted_qos):
for sub_result in granted_qos:
if sub_result == 0x80:
# error processing
print(
logger.error(
f"Could not subscribe to {self.sub_topic}. result_code={granted_qos}"
)

Expand Down Expand Up @@ -138,7 +138,7 @@ def clone_or_pull_repo(repo_url, clone_dir="repo") -> Optional[str]:
"""
if os.path.exists(clone_dir):
# If the repository exists, try to pull the latest changes
print(f"Pulling the latest changes in '{clone_dir}'...")
logger.debug(f"Pulling the latest changes in '{clone_dir}'...")

repo = git.Repo(clone_dir)
origin = repo.remotes.origin
Expand All @@ -148,29 +148,31 @@ def clone_or_pull_repo(repo_url, clone_dir="repo") -> Optional[str]:
fetch_info = origin.pull()[0]

except GitCommandError as e:
print(f"Error during git pull: {e}")
logger.error(f"Error during git pull: {e}")

if fetch_info.commit.hexsha != prev_commit.hexsha:
print("Repository updated with new changes.")
logger.info("Repository updated with new changes.")
return fetch_info.commit.hexsha

print("No new changes found. Repository is already up to date.")
logger.info("No new changes found. Repository is already up to date.")
return None
else:
# If the repository doesn't exist, clone it
print(f"Cloning the repository '{repo_url}' into '{clone_dir}'...")
logger.debug(f"Cloning the repository '{repo_url}' into '{clone_dir}'...")

try:
repo = git.Repo.clone_from(repo_url, clone_dir)
except GitCommandError as e:
print(f"Error during git clone: {e}")
logger.error(f"Error during git clone: {e}")

print(f"Repository cloned into '{clone_dir}'.")
logger.info(f"Repository cloned into '{clone_dir}'.")

return repo.head.commit.hexsha


if __name__ == "__main__":
logger = logging.getLogger(__name__)

repo_url = read_repo_url_from_toml("config.toml")
client = GittyUpClient()
try:
Expand All @@ -193,14 +195,14 @@ def clone_or_pull_repo(repo_url, clone_dir="repo") -> Optional[str]:
)

# Wait for the specified interval before checking again
print(f"Waiting for {CHECK_INTERVAL} seconds before the next pull check...")
logger.info(f"Waiting for {CHECK_INTERVAL} seconds before the next pull check...")
time.sleep(CHECK_INTERVAL)
except ConnectionRefusedError:
print("MQTT broker is not ready yet")
logger.error("MQTT broker is not ready yet")
except KeyboardInterrupt:
print("Exiting...")
logger.info("Exiting...")
if client:
client.shutdown()
sys.exit(0)
except Exception as ex:
print("Unexpected error. %s", ex)
logger.error("Unexpected error. %s", ex)

0 comments on commit 7a27c77

Please sign in to comment.