Skip to content

Commit 63fe91e

Browse files
committed
use logger.exception() in some exception handlers, disable rule forcing it over logger.error
Use logger.exception for broad catches where the exception may be useful, Use logger.error for expected cases where we know what we're dealing with already. Suppress SonarQube rule python:S8572 globally — the blanket "always use logger.exception in except blocks" recommendation doesn't fit our policy. Assisted-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 65a8cfe commit 63fe91e

14 files changed

Lines changed: 42 additions & 32 deletions

File tree

apps/dashboard_reports/tasks.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def _sync_jobs_atomically(job_results: list) -> list:
184184
try:
185185
JobData.create_or_update_from_awx(job)
186186
except Exception as e:
187-
logger.error(f"Error creating/updating JobData for job {job['id']}: {str(e)}")
187+
logger.exception(f"Error creating/updating JobData for job {job['id']}: {str(e)}")
188188
failed_jobs.append(job["id"])
189189
if failed_jobs:
190190
raise _PartialSyncRollbackError()
@@ -664,7 +664,7 @@ def cleanup_dashboard_reports_old_data(**kwargs) -> dict[str, Any]:
664664
)
665665
except Exception as e:
666666
duration_ms = (time.monotonic() - start_time) * 1000
667-
logger.error(f"Error during cleanup of old JobData records: {str(e)}")
667+
logger.exception(f"Error during cleanup of old JobData records: {str(e)}")
668668
_save_telemetry_details(
669669
task_name=task_name,
670670
success=False,

apps/dynamic_settings/management/commands/reload_config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,6 @@ def handle(self, *args, **options):
5151

5252
except Exception as e:
5353
error_msg = f"Failed to reload configuration: {str(e)}"
54-
logger.error(error_msg)
54+
logger.exception(error_msg)
5555
self.stdout.write(self.style.ERROR(f"{error_msg}"))
5656
raise

apps/dynamic_settings/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def log_setting_change(user, setting_key: str, new_value, old_value=None):
8282
return setting
8383

8484
except Exception as e:
85-
logger.error(f"Failed to log setting change for {setting_key}: {str(e)}")
85+
logger.exception(f"Failed to log setting change for {setting_key}: {str(e)}")
8686
return None
8787

8888

@@ -144,7 +144,7 @@ def rollback_configuration_change(change_id, user):
144144
}
145145

146146
except Exception as e:
147-
logger.error(f"Failed to rollback configuration change {change_id}: {str(e)}")
147+
logger.exception(f"Failed to rollback configuration change {change_id}: {str(e)}")
148148
return {"success": False, "error": f"Failed to rollback: {str(e)}"}
149149

150150

apps/tasks/cleanup/cleanup_metrics_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,5 @@ def cleanup_metrics_data(**kwargs) -> dict[str, Any]:
108108
)
109109

110110
except Exception as e:
111-
logger.error(f"Error in cleanup_metrics_data: {str(e)}")
111+
logger.exception(f"Error in cleanup_metrics_data: {str(e)}")
112112
return create_task_result("error", error=f"Cleanup failed: {str(e)}")

apps/tasks/collectors/daily_metrics_rollup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -331,5 +331,5 @@ def daily_metrics_rollup(**kwargs) -> dict[str, Any]:
331331
)
332332

333333
except Exception as e:
334-
logger.error(f"Error in daily_metrics_rollup: {str(e)}")
334+
logger.exception(f"Error in daily_metrics_rollup: {str(e)}")
335335
return create_task_result("error", error=f"Rollup failed: {str(e)}")

apps/tasks/cron_scheduler.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def start(self):
148148
logger.info(f"Periodic database sync will run every {self.check_interval} seconds")
149149

150150
except Exception as e:
151-
logger.error(f"Failed to start cron scheduler: {str(e)}")
151+
logger.exception(f"Failed to start cron scheduler: {str(e)}")
152152
raise
153153

154154
def stop(self):
@@ -163,7 +163,7 @@ def stop(self):
163163
self._db_task_jobs.clear()
164164
logger.info("Task scheduler stopped")
165165
except Exception as e:
166-
logger.error(f"Error stopping cron scheduler: {str(e)}")
166+
logger.exception(f"Error stopping cron scheduler: {str(e)}")
167167

168168
def _task_feature_flag_enabled(self, task) -> bool:
169169
"""Return False if the task carries a feature flag that is currently disabled."""
@@ -201,7 +201,7 @@ def _sync_database_tasks(self):
201201
logger.info(f"Synchronized {added_scheduled} scheduled and {added_recurring} recurring database tasks")
202202

203203
except Exception as e:
204-
logger.error(f"Error synchronizing database tasks: {e}")
204+
logger.exception(f"Error synchronizing database tasks: {e}")
205205

206206
def _periodic_database_sync(self):
207207
"""Periodically check for new database tasks and add them to the scheduler."""
@@ -376,7 +376,7 @@ def _add_database_scheduled_task(self, task):
376376
logger.info(f"Added scheduled database task: {task.name} (ID: {task.id}) at {task.scheduled_time}")
377377

378378
except Exception as e:
379-
logger.error(f"Failed to add scheduled database task {task.id}: {e}")
379+
logger.exception(f"Failed to add scheduled database task {task.id}: {e}")
380380

381381
def _add_database_recurring_task(self, task):
382382
"""Add a recurring database task to the scheduler."""
@@ -404,7 +404,7 @@ def _add_database_recurring_task(self, task):
404404
logger.info(f"Added recurring database task: {task.name} (ID: {task.id}) with cron: {task.cron_expression}")
405405

406406
except Exception as e:
407-
logger.error(f"Failed to add recurring database task {task.id}: {e}")
407+
logger.exception(f"Failed to add recurring database task {task.id}: {e}")
408408

409409
def _execute_database_task(self, task_id: int):
410410
"""Execute a database task by submitting it to dispatcherd."""
@@ -481,7 +481,7 @@ def _execute_database_task(self, task_id: int):
481481
self._remove_database_task(task_id)
482482

483483
except Exception as e:
484-
logger.error(f"Failed to execute database task {task_id}: {e}")
484+
logger.exception(f"Failed to execute database task {task_id}: {e}")
485485

486486
def _remove_database_task(self, task_id: int):
487487
"""Remove a database task from the scheduler."""

apps/tasks/dispatcherd_config.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def setup_dispatcherd_config() -> None:
6969
logger.error(f"Failed to import dispatcherd: {e}")
7070
raise
7171
except Exception as e:
72-
logger.error(f"Failed to configure dispatcherd: {e}")
72+
logger.exception(f"Failed to configure dispatcherd: {e}")
7373
raise
7474

7575

@@ -176,7 +176,7 @@ def build_config_from_django_settings() -> dict[str, Any]:
176176
return config
177177

178178
except Exception as e:
179-
logger.error(f"Failed to build config from Django settings: {e}")
179+
logger.exception(f"Failed to build config from Django settings: {e}")
180180
raise
181181

182182

@@ -199,5 +199,5 @@ def ensure_dispatcherd_configured() -> None:
199199
logger.error("Dispatcherd not available")
200200
raise
201201
except Exception as e:
202-
logger.error(f"Failed to ensure dispatcherd configuration: {e}")
202+
logger.exception(f"Failed to ensure dispatcherd configuration: {e}")
203203
raise

apps/tasks/models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ def retry(self, delay_seconds: int = 0) -> bool:
184184
submit_task_to_dispatcher(self)
185185
except Exception as e:
186186
# If submission fails, update the task status
187-
logger.error(f"Failed to submit retried task {self.id} to dispatcher: {str(e)}")
187+
logger.exception(f"Failed to submit retried task {self.id} to dispatcher: {str(e)}")
188188
self.status = "failed"
189189
self.error_message = f"Failed to submit to dispatcher: {str(e)}"
190190
self.save(update_fields=["status", "error_message", "modified"])

apps/tasks/tasks_system.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def submit_task_to_dispatcher(task: Any) -> None:
247247
if task.can_retry():
248248
logger.warning(f"Error submitting task to dispatcher: {str(e)}")
249249
else:
250-
logger.error(f"Error submitting task to dispatcher: {str(e)}")
250+
logger.exception(f"Error submitting task to dispatcher: {str(e)}")
251251

252252

253253
# runs during `manage.py metrics_service init-system-tasks`
@@ -307,7 +307,7 @@ def create_system_tasks() -> dict[str, Any]:
307307
_create_task_from_group(task_id, config, results, Task)
308308
except Exception as e:
309309
results["tasks"].append(f"Error with {task_id}: {str(e)}")
310-
logger.error(f"Failed to create task {task_id}: {e}")
310+
logger.exception(f"Failed to create task {task_id}: {e}")
311311

312312
# Restore completed status for one-shot tasks that already ran successfully,
313313
# preventing them from re-running on the next upgrade.

apps/tasks/utils.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,11 @@ def _fetch_task_by_id(task_id: int) -> Any:
3636
from .models import Task
3737

3838
return Task.objects.get(id=task_id)
39+
except Task.DoesNotExist:
40+
logger.error(f"Task instance not found for task_id: {task_id}")
41+
return None
3942
except Exception:
40-
logger.error(f"Failed to get task instance for task_id: {task_id}")
43+
logger.exception(f"Failed to get task instance for task_id: {task_id}")
4144
return None
4245

4346

@@ -47,8 +50,11 @@ def _fetch_execution_by_id(execution_id: int) -> Any:
4750
from .models import TaskExecution
4851

4952
return TaskExecution.objects.get(id=execution_id)
53+
except TaskExecution.DoesNotExist:
54+
logger.error(f"Execution instance not found for execution_id: {execution_id}")
55+
return None
5056
except Exception:
51-
logger.error(f"Failed to get execution instance for execution_id: {execution_id}")
57+
logger.exception(f"Failed to get execution instance for execution_id: {execution_id}")
5258
return None
5359

5460

@@ -118,7 +124,7 @@ def handle_task_error(
118124
)
119125

120126
except Exception as save_error:
121-
logger.error(f"Failed to update task status after error: {save_error}")
127+
logger.exception(f"Failed to update task status after error: {save_error}")
122128

123129
# Deferred past the transaction so status=="failed" and attempts are incremented before can_retry() is called.
124130
# Defaults to ERROR when no task context is available.

0 commit comments

Comments
 (0)