Skip to content

Commit 5e4b417

Browse files
Fix errors and issues in the code (#71)
Fix errors and issues in various functions across multiple files by adding proper error handling and logging. * **backend/code_parser.py** - Update `save_analysis_to_db` function to log database errors. * **backend/pipeline_manager.py** - Add logging configuration. - Update `autogpt_task` function to log API errors. - Update `pinocchio_fact_check` function to log HTTP errors and raise for status. * **chatbot/app.py** - Add logging configuration. - Update `scan_network` function to log network errors. - Update `deploy_exploit` function to log deployment errors. - Update various functions to log errors during module initialization and integration. * **chatbot/chatbot.py** - Add logging configuration. - Update `handle_vulnerability_scanning` function to log database errors. - Update `handle_exploit_deployment` function to log deployment errors. * **core/email_server/EmailServer.py** - Add logging configuration. - Update email processing to log errors. - Update image sending to log errors. * **database/models.py** - Add logging configuration. - Update `verify_component_connections` function to log component connection errors. --- For more details, open the [Copilot Workspace session](https://copilot-workspace.githubnext.com/ProjectZeroDays/Project-Red-Sword/pull/71?shareId=f212815b-649a-4a96-b513-fe28d0558230).
2 parents 2229860 + bd67df4 commit 5e4b417

File tree

6 files changed

+80
-58
lines changed

6 files changed

+80
-58
lines changed

backend/code_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def save_analysis_to_db(self, source, title, links, error):
4848
session.add(analysis_result)
4949
session.commit()
5050
except Exception as e:
51-
print(f"Error saving analysis to database: {e}")
51+
logging.error(f"Error saving analysis to database: {e}")
5252
finally:
5353
session.close()
5454

backend/pipeline_manager.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import openai
22
import requests
3+
import logging
34
from database.models import DocumentAnalysis
45
from sqlalchemy import create_engine
56
from sqlalchemy.orm import sessionmaker
@@ -8,6 +9,9 @@
89
engine = create_engine(DATABASE_URL)
910
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
1011

12+
# Configure logging
13+
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
14+
1115
class PipelineManager:
1216
def __init__(self):
1317
pass
@@ -22,7 +26,7 @@ def autogpt_task(self, task):
2226
)
2327
return response.choices[0].text.strip()
2428
except Exception as e:
25-
print(f"Error during autogpt_task: {e}")
29+
logging.error(f"Error during autogpt_task: {e}")
2630
return ""
2731

2832
def pinocchio_fact_check(self, text):
@@ -33,16 +37,17 @@ def pinocchio_fact_check(self, text):
3337
"key": "YOUR_API_KEY"
3438
}
3539
response = requests.get(url, params=params)
36-
if response.status_code == 200:
37-
result = response.json()
38-
if "claims" in result:
39-
return result["claims"]
40-
else:
41-
return "No claims found."
40+
response.raise_for_status()
41+
result = response.json()
42+
if "claims" in result:
43+
return result["claims"]
4244
else:
43-
return f"Error: {response.status_code}"
45+
return "No claims found."
46+
except requests.exceptions.HTTPError as e:
47+
logging.error(f"HTTP error during pinocchio_fact_check: {e}")
48+
return f"Error: {e}"
4449
except Exception as e:
45-
print(f"Error during pinocchio_fact_check: {e}")
50+
logging.error(f"Error during pinocchio_fact_check: {e}")
4651
return ""
4752

4853
def save_analysis_to_db(self, source, title, links, error):
@@ -57,7 +62,7 @@ def save_analysis_to_db(self, source, title, links, error):
5762
session.add(analysis_result)
5863
session.commit()
5964
except Exception as e:
60-
print(f"Error saving analysis to database: {e}")
65+
logging.error(f"Error saving analysis to database: {e}")
6166
finally:
6267
session.close()
6368

chatbot/app.py

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -39,20 +39,24 @@
3939
from kafka import KafkaProducer, KafkaConsumer
4040

4141
import os
42+
import logging
4243

4344
app = Flask(__name__)
4445

4546
DATABASE_URL = "sqlite:///document_analysis.db"
4647
engine = create_engine(DATABASE_URL)
4748
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
4849

50+
# Configure logging
51+
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
52+
4953
def scan_network():
5054
try:
5155
# Placeholder function for scanning network
5256
devices = ["Device1", "Device2", "Device3"]
5357
return devices
5458
except Exception as e:
55-
print(f"Error during network scanning: {e}")
59+
logging.error(f"Error during network scanning: {e}")
5660
return []
5761

5862
def deploy_exploit(target):
@@ -62,7 +66,7 @@ def deploy_exploit(target):
6266
return "Exploit deployed successfully!"
6367
return "Exploit deployment failed."
6468
except Exception as e:
65-
print(f"Error during exploit deployment: {e}")
69+
logging.error(f"Error during exploit deployment: {e}")
6670
return "Exploit deployment failed."
6771

6872
def save_scan_results_to_db(source, title, links, error):
@@ -77,7 +81,7 @@ def save_scan_results_to_db(source, title, links, error):
7781
session.add(scan_result)
7882
session.commit()
7983
except Exception as e:
80-
print(f"Error saving scan results to database: {e}")
84+
logging.error(f"Error saving scan results to database: {e}")
8185
finally:
8286
session.close()
8387

@@ -104,7 +108,7 @@ def deploy_exploit_endpoint():
104108
threat_intelligence = RealTimeThreatIntelligence(api_key=os.getenv("REAL_TIME_THREAT_INTELLIGENCE_API_KEY"))
105109
monitoring = RealTimeMonitoring(threat_intelligence_module=threat_intelligence)
106110
except Exception as e:
107-
print(f"Error initializing real-time threat intelligence and monitoring modules: {e}")
111+
logging.error(f"Error initializing real-time threat intelligence and monitoring modules: {e}")
108112

109113
# Initialize and integrate new modules in the main function
110114
try:
@@ -138,13 +142,13 @@ def deploy_exploit_endpoint():
138142
code_parser = CodeParser("sample_code")
139143
pipeline_manager = PipelineManager()
140144
except Exception as e:
141-
print(f"Error initializing modules: {e}")
145+
logging.error(f"Error initializing modules: {e}")
142146

143147
# Integrate the ThreatIntelligence module with RealTimeMonitoring
144148
try:
145149
monitoring.threat_intelligence_module = advanced_threat_intelligence
146150
except Exception as e:
147-
print(f"Error integrating ThreatIntelligence module with RealTimeMonitoring: {e}")
151+
logging.error(f"Error integrating ThreatIntelligence module with RealTimeMonitoring: {e}")
148152

149153
# Add real-time threat data analysis using the ThreatIntelligence module
150154
async def analyze_threat_data():
@@ -153,14 +157,14 @@ async def analyze_threat_data():
153157
analyzed_data = advanced_threat_intelligence.process_data(threat_data)
154158
return analyzed_data
155159
except Exception as e:
156-
print(f"Error analyzing threat data: {e}")
160+
logging.error(f"Error analyzing threat data: {e}")
157161

158162
# Update the RealTimeThreatIntelligence initialization to include the ThreatIntelligence module
159163
try:
160164
threat_intelligence_module = RealTimeThreatIntelligence(api_key="YOUR_API_KEY")
161165
threat_intelligence_module.threat_intelligence = advanced_threat_intelligence
162166
except Exception as e:
163-
print(f"Error updating RealTimeThreatIntelligence initialization: {e}")
167+
logging.error(f"Error updating RealTimeThreatIntelligence initialization: {e}")
164168

165169
# Add real-time threat data monitoring using the ThreatIntelligence module
166170
async def monitor_threat_data():
@@ -170,85 +174,85 @@ async def monitor_threat_data():
170174
if threat["severity"] > 0.8:
171175
monitoring.trigger_alert(threat)
172176
except Exception as e:
173-
print(f"Error monitoring threat data: {e}")
177+
logging.error(f"Error monitoring threat data: {e}")
174178

175179
# Integrate the AutomatedIncidentResponse module with RealTimeMonitoring
176180
try:
177181
monitoring.automated_incident_response = automated_incident_response
178182
except Exception as e:
179-
print(f"Error integrating AutomatedIncidentResponse module with RealTimeMonitoring: {e}")
183+
logging.error(f"Error integrating AutomatedIncidentResponse module with RealTimeMonitoring: {e}")
180184

181185
# Integrate the AIRedTeaming module with RealTimeMonitoring
182186
try:
183187
monitoring.ai_red_teaming = ai_red_teaming
184188
except Exception as e:
185-
print(f"Error integrating AIRedTeaming module with RealTimeMonitoring: {e}")
189+
logging.error(f"Error integrating AIRedTeaming module with RealTimeMonitoring: {e}")
186190

187191
# Integrate the APTSimulation module with RealTimeMonitoring
188192
try:
189193
monitoring.apt_simulation = apt_simulation()
190194
except Exception as e:
191-
print(f"Error integrating APTSimulation module with RealTimeMonitoring: {e}")
195+
logging.error(f"Error integrating APTSimulation module with RealTimeMonitoring: {e}")
192196

193197
# Integrate the PredictiveAnalytics module with RealTimeMonitoring
194198
try:
195199
monitoring.predictive_analytics = predictive_analytics
196200
except Exception as e:
197-
print(f"Error integrating PredictiveAnalytics module with RealTimeMonitoring: {e}")
201+
logging.error(f"Error integrating PredictiveAnalytics module with RealTimeMonitoring: {e}")
198202

199203
# Integrate the MachineLearningAI module with RealTimeMonitoring
200204
try:
201205
monitoring.machine_learning_ai = machine_learning_ai
202206
except Exception as e:
203-
print(f"Error integrating MachineLearningAI module with RealTimeMonitoring: {e}")
207+
logging.error(f"Error integrating MachineLearningAI module with RealTimeMonitoring: {e}")
204208

205209
# Integrate the DataVisualization module with RealTimeMonitoring
206210
try:
207211
monitoring.data_visualization = data_visualization
208212
except Exception as e:
209-
print(f"Error integrating DataVisualization module with RealTimeMonitoring: {e}")
213+
logging.error(f"Error integrating DataVisualization module with RealTimeMonitoring: {e}")
210214

211215
# Integrate the CloudExploitation module with RealTimeMonitoring
212216
try:
213217
monitoring.cloud_exploitation = cloud_exploitation
214218
except Exception as e:
215-
print(f"Error integrating CloudExploitation module with RealTimeMonitoring: {e}")
219+
logging.error(f"Error integrating CloudExploitation module with RealTimeMonitoring: {e}")
216220

217221
# Integrate the IoTExploitation module with RealTimeMonitoring
218222
try:
219223
monitoring.iot_exploitation = iot_exploitation
220224
except Exception as e:
221-
print(f"Error integrating IoTExploitation module with RealTimeMonitoring: {e}")
225+
logging.error(f"Error integrating IoTExploitation module with RealTimeMonitoring: {e}")
222226

223227
# Integrate the QuantumComputing module with RealTimeMonitoring
224228
try:
225229
monitoring.quantum_computing = quantum_computing
226230
except Exception as e:
227-
print(f"Error integrating QuantumComputing module with RealTimeMonitoring: {e}")
231+
logging.error(f"Error integrating QuantumComputing module with RealTimeMonitoring: {e}")
228232

229233
# Integrate the EdgeComputing module with RealTimeMonitoring
230234
try:
231235
monitoring.edge_computing = edge_computing
232236
except Exception as e:
233-
print(f"Error integrating EdgeComputing module with RealTimeMonitoring: {e}")
237+
logging.error(f"Error integrating EdgeComputing module with RealTimeMonitoring: {e}")
234238

235239
# Integrate the ServerlessComputing module with RealTimeMonitoring
236240
try:
237241
monitoring.serverless_computing = serverless_computing
238242
except Exception as e:
239-
print(f"Error integrating ServerlessComputing module with RealTimeMonitoring: {e}")
243+
logging.error(f"Error integrating ServerlessComputing module with RealTimeMonitoring: {e}")
240244

241245
# Integrate the MicroservicesArchitecture module with RealTimeMonitoring
242246
try:
243247
monitoring.microservices_architecture = microservices_architecture
244248
except Exception as e:
245-
print(f"Error integrating MicroservicesArchitecture module with RealTimeMonitoring: {e}")
249+
logging.error(f"Error integrating MicroservicesArchitecture module with RealTimeMonitoring: {e}")
246250

247251
# Integrate the CloudNativeApplications module with RealTimeMonitoring
248252
try:
249253
monitoring.cloud_native_applications = cloud_native_applications
250254
except Exception as e:
251-
print(f"Error integrating CloudNativeApplications module with RealTimeMonitoring: {e}")
255+
logging.error(f"Error integrating CloudNativeApplications module with RealTimeMonitoring: {e}")
252256

253257
# Add tool tips and advanced help options for all functions
254258
def add_tool_tips():
@@ -340,7 +344,7 @@ def setup_message_queue():
340344
channel.queue_declare(queue='task_queue', durable=True)
341345
return channel
342346
except Exception as e:
343-
print(f"Error setting up message queue: {e}")
347+
logging.error(f"Error setting up message queue: {e}")
344348
return None
345349

346350
def send_message(channel, message):
@@ -352,45 +356,45 @@ def send_message(channel, message):
352356
properties=pika.BasicProperties(
353357
delivery_mode=2, # make message persistent
354358
))
355-
print(f"Sent message: {message}")
359+
logging.info(f"Sent message: {message}")
356360
except Exception as e:
357-
print(f"Error sending message: {e}")
361+
logging.error(f"Error sending message: {e}")
358362

359363
def receive_message(channel):
360364
def callback(ch, method, properties, body):
361-
print(f"Received message: {body}")
365+
logging.info(f"Received message: {body}")
362366
ch.basic_ack(delivery_tag=method.delivery_tag)
363367

364368
try:
365369
channel.basic_consume(queue='task_queue', on_message_callback=callback)
366-
print('Waiting for messages. To exit press CTRL+C')
370+
logging.info('Waiting for messages. To exit press CTRL+C')
367371
channel.start_consuming()
368372
except Exception as e:
369-
print(f"Error receiving message: {e}")
373+
logging.error(f"Error receiving message: {e}")
370374

371375
def setup_kafka():
372376
try:
373377
producer = KafkaProducer(bootstrap_servers='localhost:9092')
374378
consumer = KafkaConsumer('my_topic', bootstrap_servers='localhost:9092', auto_offset_reset='earliest', enable_auto_commit=True, group_id='my-group')
375379
return producer, consumer
376380
except Exception as e:
377-
print(f"Error setting up Kafka: {e}")
381+
logging.error(f"Error setting up Kafka: {e}")
378382
return None, None
379383

380384
def send_message_to_kafka(producer, topic, message):
381385
try:
382386
producer.send(topic, message.encode('utf-8'))
383387
producer.flush()
384-
print(f"Sent message to Kafka topic {topic}: {message}")
388+
logging.info(f"Sent message to Kafka topic {topic}: {message}")
385389
except Exception as e:
386-
print(f"Error sending message to Kafka: {e}")
390+
logging.error(f"Error sending message to Kafka: {e}")
387391

388392
def receive_message_from_kafka(consumer):
389393
try:
390394
for message in consumer:
391-
print(f"Received message from Kafka: {message.value.decode('utf-8')}")
395+
logging.info(f"Received message from Kafka: {message.value.decode('utf-8')}")
392396
except Exception as e:
393-
print(f"Error receiving message from Kafka: {e}")
397+
logging.error(f"Error receiving message from Kafka: {e}")
394398

395399
if __name__ == "__main__":
396400
channel = setup_message_queue()

chatbot/chatbot.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,15 @@
5151

5252
import pika
5353
from kafka import KafkaProducer, KafkaConsumer
54+
import logging
5455

5556
DATABASE_URL = "sqlite:///document_analysis.db"
5657
engine = create_engine(DATABASE_URL)
5758
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
5859

60+
# Configure logging
61+
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
62+
5963
def get_response(user_input):
6064
"""Handle user input and provide responses."""
6165
responses = {
@@ -86,13 +90,13 @@ def handle_vulnerability_scanning():
8690
session.add(scan_result)
8791
session.commit()
8892
except Exception as e:
89-
print(f"Error saving scan results to database: {e}")
93+
logging.error(f"Error saving scan results to database: {e}")
9094
finally:
9195
session.close()
9296

9397
return vulnerabilities
9498
except Exception as e:
95-
print(f"Error during vulnerability scanning: {e}")
99+
logging.error(f"Error during vulnerability scanning: {e}")
96100
return []
97101

98102
def handle_exploit_deployment(target):
@@ -112,13 +116,13 @@ def handle_exploit_deployment(target):
112116
session.add(exploit_result)
113117
session.commit()
114118
except Exception as e:
115-
print(f"Error saving exploit deployment results to database: {e}")
119+
logging.error(f"Error saving exploit deployment results to database: {e}")
116120
finally:
117121
session.close()
118122

119123
return "Exploit deployed successfully!" if result else "Exploit deployment failed."
120124
except Exception as e:
121-
print(f"Error during exploit deployment: {e}")
125+
logging.error(f"Error during exploit deployment: {e}")
122126
return "Exploit deployment failed."
123127

124128
def setup_kafka():

0 commit comments

Comments
 (0)