|
| 1 | +"""DICOM operation logging module for tracking worklist queries and DICOM sends""" |
| 2 | + |
| 3 | +import json |
| 4 | +from pathlib import Path |
| 5 | +from datetime import datetime |
| 6 | +from typing import List, Dict, Optional |
| 7 | +from enum import Enum |
| 8 | +import threading |
| 9 | + |
| 10 | + |
| 11 | +class DicomOperationType(str, Enum): |
| 12 | + WORKLIST_QUERY = "worklist_query" |
| 13 | + WORKLIST_QUERY_ALL = "worklist_query_all" |
| 14 | + DICOM_SEND = "dicom_send" |
| 15 | + DICOM_VERIFY = "dicom_verify" |
| 16 | + |
| 17 | + |
| 18 | +class DicomLogger: |
| 19 | + """Thread-safe logger for DICOM operations""" |
| 20 | + |
| 21 | + _instance = None |
| 22 | + _lock = threading.Lock() |
| 23 | + |
| 24 | + def __new__(cls): |
| 25 | + if cls._instance is None: |
| 26 | + with cls._lock: |
| 27 | + if cls._instance is None: |
| 28 | + cls._instance = super().__new__(cls) |
| 29 | + cls._instance._initialized = False |
| 30 | + return cls._instance |
| 31 | + |
| 32 | + def __init__(self): |
| 33 | + if self._initialized: |
| 34 | + return |
| 35 | + |
| 36 | + self._initialized = True |
| 37 | + self._file_lock = threading.Lock() |
| 38 | + self.log_file = Path(__file__).parent.parent / "dicom_logs.json" |
| 39 | + self.max_logs = 500 # Keep last 500 entries |
| 40 | + |
| 41 | + # Initialize log file if it doesn't exist |
| 42 | + if not self.log_file.exists(): |
| 43 | + self._save_logs([]) |
| 44 | + |
| 45 | + def _load_logs(self) -> List[Dict]: |
| 46 | + """Load logs from file""" |
| 47 | + try: |
| 48 | + if self.log_file.exists(): |
| 49 | + content = self.log_file.read_text() |
| 50 | + if content.strip(): |
| 51 | + return json.loads(content) |
| 52 | + return [] |
| 53 | + except (json.JSONDecodeError, IOError): |
| 54 | + return [] |
| 55 | + |
| 56 | + def _save_logs(self, logs: List[Dict]) -> None: |
| 57 | + """Save logs to file""" |
| 58 | + with self._file_lock: |
| 59 | + self.log_file.write_text(json.dumps(logs, indent=2)) |
| 60 | + |
| 61 | + def log( |
| 62 | + self, |
| 63 | + operation_type: DicomOperationType, |
| 64 | + success: bool, |
| 65 | + message: str, |
| 66 | + details: Optional[Dict] = None |
| 67 | + ) -> None: |
| 68 | + """Add a log entry""" |
| 69 | + entry = { |
| 70 | + "timestamp": datetime.now().isoformat(), |
| 71 | + "operation": operation_type.value, |
| 72 | + "success": success, |
| 73 | + "message": message, |
| 74 | + "details": details or {} |
| 75 | + } |
| 76 | + |
| 77 | + logs = self._load_logs() |
| 78 | + logs.insert(0, entry) # Add to beginning (newest first) |
| 79 | + |
| 80 | + # Trim to max size |
| 81 | + if len(logs) > self.max_logs: |
| 82 | + logs = logs[:self.max_logs] |
| 83 | + |
| 84 | + self._save_logs(logs) |
| 85 | + |
| 86 | + def log_worklist_query( |
| 87 | + self, |
| 88 | + success: bool, |
| 89 | + message: str, |
| 90 | + host: str, |
| 91 | + port: int, |
| 92 | + ae_title: str, |
| 93 | + calling_ae: str, |
| 94 | + patient_name: Optional[str] = None, |
| 95 | + patient_id: Optional[str] = None, |
| 96 | + accession_number: Optional[str] = None, |
| 97 | + modality: Optional[str] = None, |
| 98 | + results_count: int = 0 |
| 99 | + ) -> None: |
| 100 | + """Log a worklist query operation""" |
| 101 | + details = { |
| 102 | + "host": host, |
| 103 | + "port": port, |
| 104 | + "ae_title": ae_title, |
| 105 | + "calling_ae": calling_ae, |
| 106 | + "filters": { |
| 107 | + "patient_name": patient_name, |
| 108 | + "patient_id": patient_id, |
| 109 | + "accession_number": accession_number, |
| 110 | + "modality": modality |
| 111 | + }, |
| 112 | + "results_count": results_count |
| 113 | + } |
| 114 | + self.log(DicomOperationType.WORKLIST_QUERY, success, message, details) |
| 115 | + |
| 116 | + def log_worklist_query_all( |
| 117 | + self, |
| 118 | + success: bool, |
| 119 | + message: str, |
| 120 | + host: str, |
| 121 | + port: int, |
| 122 | + ae_title: str, |
| 123 | + ae_titles_queried: int, |
| 124 | + successful_queries: int, |
| 125 | + results_count: int |
| 126 | + ) -> None: |
| 127 | + """Log a query-all worklist operation""" |
| 128 | + details = { |
| 129 | + "host": host, |
| 130 | + "port": port, |
| 131 | + "ae_title": ae_title, |
| 132 | + "ae_titles_queried": ae_titles_queried, |
| 133 | + "successful_queries": successful_queries, |
| 134 | + "results_count": results_count |
| 135 | + } |
| 136 | + self.log(DicomOperationType.WORKLIST_QUERY_ALL, success, message, details) |
| 137 | + |
| 138 | + def log_dicom_send( |
| 139 | + self, |
| 140 | + success: bool, |
| 141 | + message: str, |
| 142 | + destination_name: str, |
| 143 | + host: str, |
| 144 | + port: int, |
| 145 | + ae_title: str, |
| 146 | + calling_ae: str, |
| 147 | + file_path: Optional[str] = None, |
| 148 | + patient_id: Optional[str] = None, |
| 149 | + patient_name: Optional[str] = None, |
| 150 | + study_uid: Optional[str] = None, |
| 151 | + accession_number: Optional[str] = None |
| 152 | + ) -> None: |
| 153 | + """Log a DICOM send operation""" |
| 154 | + details = { |
| 155 | + "destination": { |
| 156 | + "name": destination_name, |
| 157 | + "host": host, |
| 158 | + "port": port, |
| 159 | + "ae_title": ae_title, |
| 160 | + "calling_ae": calling_ae |
| 161 | + }, |
| 162 | + "file_path": file_path, |
| 163 | + "patient_id": patient_id, |
| 164 | + "patient_name": patient_name, |
| 165 | + "study_uid": study_uid, |
| 166 | + "accession_number": accession_number |
| 167 | + } |
| 168 | + self.log(DicomOperationType.DICOM_SEND, success, message, details) |
| 169 | + |
| 170 | + def log_dicom_verify( |
| 171 | + self, |
| 172 | + success: bool, |
| 173 | + message: str, |
| 174 | + destination_name: str, |
| 175 | + host: str, |
| 176 | + port: int, |
| 177 | + ae_title: str, |
| 178 | + calling_ae: str |
| 179 | + ) -> None: |
| 180 | + """Log a DICOM verification (C-ECHO) operation""" |
| 181 | + details = { |
| 182 | + "destination": { |
| 183 | + "name": destination_name, |
| 184 | + "host": host, |
| 185 | + "port": port, |
| 186 | + "ae_title": ae_title, |
| 187 | + "calling_ae": calling_ae |
| 188 | + } |
| 189 | + } |
| 190 | + self.log(DicomOperationType.DICOM_VERIFY, success, message, details) |
| 191 | + |
| 192 | + def get_logs( |
| 193 | + self, |
| 194 | + operation_type: Optional[DicomOperationType] = None, |
| 195 | + success: Optional[bool] = None, |
| 196 | + limit: int = 100, |
| 197 | + offset: int = 0 |
| 198 | + ) -> tuple[List[Dict], int]: |
| 199 | + """ |
| 200 | + Get log entries with optional filtering |
| 201 | +
|
| 202 | + Returns: |
| 203 | + tuple: (logs, total_count) |
| 204 | + """ |
| 205 | + logs = self._load_logs() |
| 206 | + |
| 207 | + # Filter by operation type |
| 208 | + if operation_type: |
| 209 | + logs = [l for l in logs if l.get("operation") == operation_type.value] |
| 210 | + |
| 211 | + # Filter by success status |
| 212 | + if success is not None: |
| 213 | + logs = [l for l in logs if l.get("success") == success] |
| 214 | + |
| 215 | + total_count = len(logs) |
| 216 | + |
| 217 | + # Apply pagination |
| 218 | + logs = logs[offset:offset + limit] |
| 219 | + |
| 220 | + return logs, total_count |
| 221 | + |
| 222 | + def clear_logs(self) -> None: |
| 223 | + """Clear all logs""" |
| 224 | + self._save_logs([]) |
| 225 | + |
| 226 | + |
| 227 | +# Singleton instance |
| 228 | +dicom_logger = DicomLogger() |
0 commit comments