-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding logging for Hydrography scripts #31
base: main
Are you sure you want to change the base?
Conversation
PR Reviewer Guide 🔍(Review updated until commit c221f25)
|
PR Code Suggestions ✨
|
Fixed logging configurationUpdated the logging configuration to use a path specified in the Commit:Code Improvementdef main() -> None:
...
# Configure logging after loading config
log_file_path = config["logging"].get("log_file_path", "hydrography-pipeline.log")
logging.basicConfig(
filename=log_file_path, # Use the path from the configuration
level=logging.INFO,
format="%(asctime)s - [%(levelname)s] - (%(filename)s).%(funcName)s - %(message)s",
)
... |
Error Handling for Layer LoadingImproved error handling for layer loading by adding detailed logging and maintaining process integrity. The function now logs specific errors if layers fail to load and exits immediately, as retries are not practical given the likely file path issues. Continuing without these layers is not possible since subsequent processes depend on their successful loading. CommitCode Improvementfrom typing import Optional, Tuple
from qgis.core import QgsVectorLayer
def load_layers(nbi_points_fp: str, osm_fp: str, logger) -> Tuple[Optional[QgsVectorLayer], Optional[QgsVectorLayer]]:
"""
Load required layers with improved error handling.
Args:
nbi_points_fp (str): File path to the NBI points layer.
osm_fp (str): File path to the OSM ways layer.
logger: Logger instance for logging errors.
Returns:
Tuple[Optional[QgsVectorLayer], Optional[QgsVectorLayer]]:
A tuple containing the NBI points layer and the OSM ways layer.
"""
def load_layer(fp: str, layer_name: str) -> Optional[QgsVectorLayer]:
"""
Load a layer and log errors if the loading fails.
Args:
fp (str): File path to the layer.
layer_name (str): Name of the layer for logging purposes.
Returns:
Optional[QgsVectorLayer]: Loaded layer or None if failed.
"""
layer = QgsVectorLayer(fp, layer_name, "ogr")
if not layer.isValid():
logger.error(f"{layer_name} layer failed to load. Check the file path and ensure the file exists.")
return None
return layer
nbi_points_gl = load_layer(nbi_points_fp, "nbi-points")
osm_gl = load_layer(osm_fp, "filtered")
if nbi_points_gl is None:
logger.error("NBI points layer is critical and could not be loaded. Exiting.")
sys.exit(1)
if osm_gl is None:
logger.error("OSM ways layer could not be loaded. Exiting.")
sys.exit(1)
return nbi_points_gl, osm_gl |
Improved Error Handling for CSV WritingEnhanced the robustness of the CSV file creation process by adding error handling for potential I/O errors. Previously, if there was an issue writing the CSV file, the application would fail silently without providing any indication of the failure. CommitCode Improvement
try:
df.to_csv(intermediate_association)
logger.info(f"{intermediate_association} file has been created successfully!")
except IOError as e:
logger.error(f"Failed to write {intermediate_association}: {str(e)}") |
Ensure directory existence before useThis change adds a check to see if directories already exist before attempting to create them. It also includes logging for both successful directory creation and pre-existing directories. CommitCode Improvement
def create_directories(config: Dict[str, str]) -> None:
"""
Create directories for output data as specified in the configuration.
:param config: Dictionary containing paths for directories to be created.
"""
output_folders = config.get("output_data_folders", {})
# Define required folder keys
required_folders = ["state_folder", "csv_files", "gpkg_files", "pbf_files"]
for folder in required_folders:
folder_path = output_folders.get(folder)
if folder_path:
if not os.path.exists(folder_path):
try:
os.makedirs(folder_path)
logger.info(f"Directory created: {folder_path}")
except Exception as e:
logger.error(f"Failed to create directory {folder_path}: {e}")
else:
logger.info(f"Directory already exists: {folder_path}")
else:
logger.warning(f"Path for {folder} not specified in configuration.") This ensures directories are only created if they do not already exist and provides better feedback during execution. |
/review |
Persistent review updated to latest commit c221f25 |
Improved Error Handling in
|
PR Type
enhancement, other
Description
logger
parameter to multiple functions across various scripts to replaceprint
statements with logging.run-hydrography-pipeline.py
.Changes walkthrough 📝
determine_final_osm_id.py
Add logging to association functions
hydrography-approach/processing_scripts/associate_data/determine_final_osm_id.py
logger
parameter to multiple functions.print
statements withlogger.info
for logging.exclude_nearby_bridges.py
Add logging to exclude nearby bridges
hydrography-approach/processing_scripts/associate_data/exclude_nearby_bridges.py
logger
parameter to functions.print
statements withlogger.info
.join_all_data.py
Add logging to join all data script
hydrography-approach/processing_scripts/associate_data/join_all_data.py
logger
parameter toprocess_all_join
function.print
statements withlogger.info
.filter_osm_ways.py
Add logging to filter OSM ways
hydrography-approach/processing_scripts/filter_data/filter_osm_ways.py
logger
parameter tofilter_ways
function.print
statements withlogger.info
.process_filter_nbi_bridges.py
Add logging to filter NBI bridges
hydrography-approach/processing_scripts/filter_data/process_filter_nbi_bridges.py
logger
parameter to functions.print
statements withlogger.info
.tag_nbi_and_osm_data.py
Add logging to tag NBI and OSM data
hydrography-approach/processing_scripts/tag_data/tag_nbi_and_osm_data.py
logger
parameter to multiple functions.print
statements withlogger.info
andlogger.error
.run-hydrography-pipeline.py
Add logging to hydrography pipeline script
hydrography-approach/run-hydrography-pipeline.py
print
statements withlogging.info
.logger
to various processing functions.