Skip to content

Commit

Permalink
380 remove useless statements from log file (#478)
Browse files Browse the repository at this point in the history
* Simplify logging

* Fix black

* Fix deleting files in hydromts
  • Loading branch information
dladrichem authored Jul 23, 2024
1 parent 0cad639 commit 0b06f91
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 9 deletions.
5 changes: 3 additions & 2 deletions flood_adapt/integrator/fiat_adapter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import gc
import logging
from pathlib import Path
from typing import List, Optional, Union

Expand All @@ -25,8 +26,8 @@ class FiatAdapter:
def __init__(self, model_root: str, database_path: str) -> None:
"""Load FIAT model based on a root directory."""
# Load FIAT template
self._logger = FloodAdaptLogging.getLogger(__name__)
self.fiat_model = FiatModel(root=model_root, mode="r", logger=self._logger)
self._logger = FloodAdaptLogging.getLogger(__name__, level=logging.INFO)
self.fiat_model = FiatModel(root=model_root, mode="r")
self.fiat_model.read()

# Get site information
Expand Down
5 changes: 3 additions & 2 deletions flood_adapt/integrator/sfincs_adapter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import gc
import logging
import os
from pathlib import Path
from typing import Optional, Union
Expand Down Expand Up @@ -41,8 +42,8 @@ def __init__(self, site: Site, model_root: Optional[str] = None):
Args:
model_root (str, optional): Root directory of overland sfincs model. Defaults to None.
"""
self._logger = FloodAdaptLogging.getLogger(__name__)
self.sf_model = SfincsModel(root=model_root, mode="r+", logger=self._logger)
self._logger = FloodAdaptLogging.getLogger(__name__, level=logging.INFO)
self.sf_model = SfincsModel(root=model_root, mode="r+")
self.sf_model.read()
self.site = site

Expand Down
27 changes: 24 additions & 3 deletions flood_adapt/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,32 @@ def remove_file_handler(cls, file_path: str) -> None:
cls.getLogger().removeHandler(handler)

@classmethod
def getLogger(cls, name: str = None) -> logging.Logger:
def getLogger(cls, name: str = None, level: int = None) -> logging.Logger:
"""Get a logger with the specified name. If no name is provided, return the root logger.
If the logger does not exist, it is created with the specified level. If no level is provided, the logger inherits the level of the root logger.
Parameters
----------
name : str, optional
The name of the logger. If not provided, the root logger is returned.
level : int, optional
The level of the logger. If not provided, the logger inherits the level of the root logger.
Returns
-------
logging.Logger
The logger with the specified name.
"""
if name is None:
return cls._root_logger
logger = cls._root_logger
else:
logger = logging.getLogger(f"FloodAdapt.{name}")

if level is not None:
logger.setLevel(level)

return logging.getLogger(f"FloodAdapt.{name}")
return logger

@classmethod
def shutdown(cls):
Expand Down
7 changes: 5 additions & 2 deletions flood_adapt/object_model/hazard/hazard.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ class Hazard:

def __init__(self, scenario: ScenarioModel, database, results_dir: Path) -> None:
self._logger = FloodAdaptLogging.getLogger(__name__)

self._mode: Mode
self.simulation_paths: List[Path]
self.simulation_paths_offshore: List[Path]
Expand Down Expand Up @@ -273,6 +272,9 @@ def run_sfincs(self):

run_success = True
for simulation_path in self.simulation_paths:
self._logger.info(
f"Running SFINCS model for {'-'.join(simulation_path.parts[-2:])}."
)
with cd(simulation_path):
sfincs_log = "sfincs.log"
# with open(results_dir.joinpath(f"{self.name}.log"), "a") as log_handler:
Expand Down Expand Up @@ -977,7 +979,7 @@ def calculate_rp_floodmaps(self):
np.copy(zb), len(floodmap_rp), 1
) # if not flooded (i.e. not in valid_cells) revert to bed_level, read from SFINCS results so it is the minimum bed level in a grid cell

self._logger.info("Calculating flood risk maps, this may take some time...")
self._logger.info("Calculating flood risk map data, this may take some time...")
for jj in valid_cells: # looping over all non-masked cells.
# linear interpolation for all return periods to evaluate
h[:, jj] = np.interp(
Expand All @@ -998,6 +1000,7 @@ def calculate_rp_floodmaps(self):
h[dry] = np.nan

for ii, rp in enumerate(floodmap_rp):
self._logger.info(f"Creating flood risk map for return period {rp} years.")
# #create single nc
zs_rp_single = xr.DataArray(
data=h[ii, :], coords={"z": zs["z"]}, attrs={"units": "meters"}
Expand Down

0 comments on commit 0b06f91

Please sign in to comment.