diff --git a/notebooks/test/test-logging.ipynb b/notebooks/test/test-logging.ipynb index eee72a5a3f3172b31c277850786fbf408d8ef968..f09b1109e399582ea24e76c9a22d05a0c9873a93 100644 --- a/notebooks/test/test-logging.ipynb +++ b/notebooks/test/test-logging.ipynb @@ -97,7 +97,7 @@ "source": [ "from cal_tools.exceptions import CalibrationError\n", "\n", - "raise CalibrationError('Calibration Failure')" + "raise CalibrationError('Testing Calibration Failure!')" ] } ], diff --git a/src/xfel_calibrate/setup_logging.py b/src/xfel_calibrate/setup_logging.py index 4714054efb05c31f504f9ef1ff870e9767a68421..8d1bf40ffe4655b33cdf5d822be2f7e1a325ee8c 100644 --- a/src/xfel_calibrate/setup_logging.py +++ b/src/xfel_calibrate/setup_logging.py @@ -9,9 +9,24 @@ from typing import Type, Any from cal_tools.warnings import CalibrationWarning +JOB_ID = os.getenv('SLURM_JOB_ID', 'local') + + def get_class_hierarchy(cls: Type) -> str: """Get the full class hierarchy of a class.""" - return '.'.join(c.__name__ for c in cls.__mro__) + return ".".join(c.__name__ for c in cls.__mro__ if c != object) + + +def get_log_info( + message: str, + log_type: Type[Exception] | Type[Warning] +) -> dict: + """Create a dictionary with log information.""" + return { + "timestamp": datetime.now().isoformat(), + "message": message, + "class": get_class_hierarchy(log_type), + } def log_error( @@ -21,16 +36,10 @@ def log_error( ) -> None: """Log error information to file.""" try: - error_info = { - "timestamp": datetime.now().isoformat(), - "job_id": os.getenv('SLURM_JOB_ID', 'local'), - "level": "ERROR", - "message": str(exc_value), - "class": get_class_hierarchy(exc_type), - } + error_info = get_log_info(str(exc_value), exc_type) - with open(f"errors_{error_info['job_id']}.log", "a") as error_log_file: - error_log_file.write(json.dumps(error_info) + "\n") + with open(f"errors_{JOB_ID}.log", "a") as log_file: + log_file.write(json.dumps(error_info) + "\n") except Exception as e: sys.stdout.write(f"Logging failed: {e}\n") @@ -45,18 +54,10 @@ def handle_warning( """Log and display warnings.""" try: - warning_info = { - "timestamp": datetime.now().isoformat(), - "job_id": os.getenv('SLURM_JOB_ID', 'local'), - "level": "WARNING", - "message": str(message), - "class": get_class_hierarchy(category), - } - - with open( - f"warnings_{warning_info['job_id']}.log", "a" - ) as warning_log_file: - warning_log_file.write(json.dumps(warning_info) + "\n") + warning_info = get_log_info(str(message), category) + + with open(f"warnings_{JOB_ID}.log", "a") as log_file: + log_file.write(json.dumps(warning_info) + "\n") except Exception as e: sys.stdout.write(f"Warning logging failed: {e}\n")