Skip to content

Commit cf3effb

Browse files
Merge pull request #242 from webtech-network/229-td-replace-print-calls-with-logging
229 td replace print calls with logging
2 parents 15f85a4 + c5de9a4 commit cf3effb

4 files changed

Lines changed: 26 additions & 14 deletions

File tree

autograder/services/template_library_service.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,13 @@
77
This is a singleton service that should be instantiated once at application startup.
88
"""
99

10+
import logging
1011
from typing import Dict, List, Optional
1112
from autograder.models.abstract.template import Template
1213
from autograder.template_library import TEMPLATE_REGISTRY, get_template_instance
1314

15+
logger = logging.getLogger(__name__)
16+
1417

1518
class TemplateLibraryService:
1619
"""
@@ -50,7 +53,7 @@ def _load_all_templates(self):
5053
self._templates[template_name] = get_template_instance(template_name)
5154
except Exception as e:
5255
# Log the error but continue loading other templates
53-
print(f"Warning: Failed to load template '{template_name}': {e}")
56+
logger.warning("Failed to load template '%s': %s", template_name, e)
5457

5558
@classmethod
5659
def get_instance(cls) -> 'TemplateLibraryService':

autograder/services/upstash_driver.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import json
2+
import logging
23
import os
34
from dotenv import load_dotenv
45
from upstash_redis import Redis
56

7+
logger = logging.getLogger(__name__)
8+
69
load_dotenv() #TODO: place this in application startup
710
class UpstashDriver:
811
def __init__(self):
@@ -49,11 +52,11 @@ def create_user(self, username: str):
4952
"quota": 10,
5053
"score": -1.0
5154
})
52-
print(f"User '{username}' created.")
55+
logger.info("User '%s' created.", username)
5356

5457
def set_score(self, username: str, score: float):
5558
"""Function to set the score of a user"""
5659
key = f"user:{username}"
5760
self.redis.hset(key, "score", score)
58-
print(f"Score '{score}' set for user '{username}'.")
61+
logger.info("Score '%s' set for user '%s'.", score, username)
5962

autograder/utils/executors/ai_executor.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
import json
2+
import logging
23
from typing import List, Dict
34
from openai import OpenAI
45
from autograder.models.dataclass.test_result import TestResult
56
from pydantic import BaseModel, Field
67
import dotenv
78
from autograder.utils.secrets_fetcher import get_secret
89

10+
logger = logging.getLogger(__name__)
11+
912
dotenv.load_dotenv() # Load environment variables from .env file
1013

1114
class TestInput(BaseModel):
@@ -73,20 +76,20 @@ def mapback(self):
7376
It finds the corresponding TestResult by matching the test name.
7477
"""
7578
if not self.test_results:
76-
print("No test results to map back.")
79+
logger.warning("No test results to map back.")
7780
return
7881

7982
for ai_result in self.test_results:
8083
# Find the corresponding TestResult reference by matching the test name
8184
matching_refs = [ref for ref in self.test_result_references if ref.test_name == ai_result.title]
8285
if matching_refs:
8386
ref = matching_refs[0]
84-
print("Found matching TestResult for AI result:",ref)
87+
logger.debug("Found matching TestResult for AI result: %s", ref)
8588
ref.score = ai_result.score
8689
ref.report = ai_result.feedback
87-
print(f"Mapped AI result '{ai_result.title}' with score {ai_result.score} to TestResult.")
90+
logger.info("Mapped AI result '%s' with score %s to TestResult.", ai_result.title, ai_result.score)
8891
else:
89-
print(f"No matching TestResult found for AI result '{ai_result.title}'.")
92+
logger.warning("No matching TestResult found for AI result '%s'.", ai_result.title)
9093

9194

9295

@@ -151,10 +154,10 @@ def stop(self):
151154
lembre-se: os nomes dos testes devem corresponder exatamente aos nomes fornecidos na lista de testes. não mude a formatação ou a estrutura dos titulos dos tests.
152155
153156
"""
154-
print("System Prompt:\n", system_prompt)
155-
print("User Prompt:\n", user_prompt)
157+
logger.debug("System Prompt:\n%s", system_prompt)
158+
logger.debug("User Prompt:\n%s", user_prompt)
156159
try:
157-
print("Sending AI engine batch request...\n")
160+
logger.info("Sending AI engine batch request...")
158161
response = self.client.responses.parse(
159162
model="o4-mini-2025-04-16",
160163
input=[
@@ -167,12 +170,12 @@ def stop(self):
167170
# Extracts and logs the results
168171
self.test_results = response.output[1].content[0].parsed.results
169172
for test_result in self.test_results:
170-
print(f"""{test_result}\n""")
173+
logger.debug("AI test result: %s", test_result)
171174
self.mapback()
172175
return self.test_result_references
173176

174177
except Exception as e:
175-
print(f"An error occurred while running the AI tests: {e}")
178+
logger.error("An error occurred while running the AI tests: %s", e)
176179
return []
177180

178181

autograder/utils/secrets_fetcher.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
# https://aws.amazon.com/developer/language/python/
44

55
import boto3
6-
import os
76
import json
7+
import logging
8+
import os
89
from botocore.exceptions import ClientError
910

11+
logger = logging.getLogger(__name__)
12+
1013
def get_secret(secret_key : str, secret_name : str = None, region : str = "us-east-1"):
1114
"""
1215
Fetches a secret value, adapting to the environment.
@@ -32,7 +35,7 @@ def get_secret(secret_key : str, secret_name : str = None, region : str = "us-ea
3235
# In production, get the key from Secrets Manager
3336
return _get_secret_from_manager(secret_name, secret_key, region)
3437
# In development, get the key from a local environment variable
35-
print("Fetching secret from local environment variable...")
38+
logger.debug("Fetching secret from local environment variable...")
3639
api_key = os.environ.get(secret_key)
3740
if not api_key:
3841
raise ValueError("Environment variable not set for development.")

0 commit comments

Comments
 (0)