Skip to content

Commit 4727292

Browse files
authored
DAS-2382: Improve internal logging handling. (#47)
1 parent 8fd0547 commit 4727292

12 files changed

Lines changed: 61 additions & 28 deletions

File tree

.github/pull_request_template.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ A short description of the changes in this PR.
1212
* [ ] Jira ticket acceptance criteria met.
1313
* [ ] `CHANGELOG.md` updated to include high level summary of PR changes and link to release.
1414
* [ ] `docker/service_version.txt` updated if publishing a release.
15+
* [ ] Jira Smart Checklist item `harmony-regridder-X.Y.Z` added Ticket
1516
* [ ] Tests added/updated and passing.
1617
* [ ] Documentation updated (if needed).

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,13 @@ The Harmony Regridding Service follows semantic versioning. All notable changes
44
to this project will be documented in this file. The format is based on [Keep a
55
Changelog](http://keepachangelog.com/en/1.0.0/).
66

7+
## [v1.9.1] - 2025-10-14
8+
9+
### Changed
10+
11+
- Changed internal handling of logging to ensure all logs are included with appropriate metadata when running as a harmony service.
12+
13+
714
## [v1.9.0] - 2025-10-08
815

916
### Added
@@ -172,6 +179,7 @@ include updated documentation and files outlined by the
172179
For more information on internal releases prior to NASA open-source approval,
173180
see legacy-CHANGELOG.md.
174181

182+
[v1.9.1]: https://github.com/nasa/harmony-regridding-service/releases/tag/1.9.1
175183
[v1.9.0]: https://github.com/nasa/harmony-regridding-service/releases/tag/1.9.0
176184
[v1.8.0]: https://github.com/nasa/harmony-regridding-service/releases/tag/1.8.0
177185
[v1.7.1]: https://github.com/nasa/harmony-regridding-service/releases/tag/1.7.1

docker/service_version.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.9.0
1+
1.9.1

harmony_regridding_service/adapter.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
)
2727
from pystac import Asset, Catalog, Item
2828

29+
from harmony_regridding_service import log_context
2930
from harmony_regridding_service.exceptions import (
3031
InvalidInterpolationMethod,
3132
InvalidTargetCRS,
@@ -45,6 +46,7 @@ class RegriddingServiceAdapter(BaseHarmonyAdapter):
4546
def __init__(self, message, catalog=None, config=None):
4647
"""Initialize the custom adapter."""
4748
super().__init__(message, catalog=catalog, config=config)
49+
log_context.set_logger(self.logger)
4850
self.cache = {'grids': {}}
4951

5052
def invoke(self) -> Catalog:

harmony_regridding_service/file_io.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Module that handles source file copy and writing to target output."""
22

3-
from logging import getLogger
43
from mimetypes import guess_type as guess_mime_type
54
from os.path import splitext
65
from pathlib import PurePath
@@ -13,8 +12,7 @@
1312
)
1413

1514
from harmony_regridding_service.exceptions import SourceDataError
16-
17-
logger = getLogger(__name__)
15+
from harmony_regridding_service.log_context import get_logger
1816

1917
KNOWN_MIME_TYPES = {
2018
'.nc4': 'application/x-netcdf4',
@@ -145,7 +143,7 @@ def clone_variables(
145143
if s_var.dtype == str and s_var.shape == ():
146144
t_var[0] = s_var[0]
147145
else:
148-
logger.error('Unable to clone variable {s_var}')
146+
get_logger().error('Unable to clone variable {s_var}')
149147
raise SourceDataError('Unhandled variable clone') from vlen_error
150148

151149
return variables

harmony_regridding_service/grid.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""Module for accessing and creating grid parameters."""
22

33
from collections.abc import Iterable
4-
from logging import getLogger
54
from typing import Any
65

76
import numpy as np
@@ -34,13 +33,12 @@
3433
InvalidTargetGrid,
3534
SourceDataError,
3635
)
36+
from harmony_regridding_service.log_context import get_logger
3737
from harmony_regridding_service.message_utilities import (
3838
get_message_crs,
3939
target_crs_from_message,
4040
)
4141

42-
logger = getLogger(__name__)
43-
4442

4543
def compute_target_areas(
4644
message: HarmonyMessage,
@@ -86,6 +84,7 @@ def compute_target_areas(
8684
filepath, var_info, target_crs
8785
)
8886

87+
logger = get_logger()
8988
logger.debug('Using TARGET Area Definitions:')
9089
for dim_pair, area in area_definitions.items():
9190
logger.debug(f'dim_pair: {dim_pair}')
@@ -128,7 +127,7 @@ def create_target_areas_from_source(
128127
dimension_pairs = get_resampled_dimension_pairs(var_info)
129128
target_areas = {}
130129
for dim_pair in dimension_pairs:
131-
logger.info(f'Generating Target Areas from Source for: {dim_pair}')
130+
get_logger().info(f'Generating Target Areas from Source for: {dim_pair}')
132131
projected_area = create_area_definition_for_projected_source_grid(
133132
filepath, dim_pair, var_info
134133
)
@@ -168,6 +167,7 @@ def convert_projected_area_to_geographic(
168167
area_extent=geographic_extent,
169168
resolution=resolution,
170169
)
170+
logger = get_logger()
171171
logger.debug(f'Source projected Area: {projected_area}')
172172
logger.debug(f'Converted Geographic Area: {geographic_area}')
173173

@@ -311,7 +311,7 @@ def get_area_definition_from_message(
311311

312312
projection = message.format.crs or 'EPSG:4326'
313313

314-
logger.info(
314+
get_logger().info(
315315
f'Creating target area from message:\n'
316316
f'proj:{projection}\n'
317317
f'area_extent:{area_extent}\n'
@@ -375,6 +375,7 @@ def compute_horizontal_source_grids(
375375
"""
376376
row_dim = get_row_dims(grid_dimensions, var_info)[0]
377377
column_dim = get_column_dims(grid_dimensions, var_info)[0]
378+
logger = get_logger()
378379
logger.info(f'found row_dim: {row_dim}')
379380
logger.info(f'found column_dim: {column_dim}')
380381

@@ -452,7 +453,7 @@ def create_area_definition_for_projected_source_grid(
452453
resolution=(cell_width, cell_height),
453454
)
454455
except Exception as e:
455-
logger.error(e)
456+
get_logger().error(e)
456457
raise SourceDataError('cannot compute projected source grids') from e
457458

458459

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""Logging Context.
2+
3+
This module is used to capture the logging context from harmony and allow easy
4+
access to all of the modules in this service.
5+
6+
We are capturing the logger that harmony service lib has created and allowing
7+
all of the modules in the service to access and use without having to pass a
8+
logging object in each function signature.
9+
10+
"""
11+
12+
from logging import getLogger
13+
14+
_LOGGER = None
15+
16+
17+
def set_logger(logger):
18+
"""Set the logger context for this request's session."""
19+
global _LOGGER
20+
_LOGGER = logger
21+
22+
23+
def get_logger(default_name='harmony-service.regridder'):
24+
"""Get the context logger or fall back to module logger."""
25+
return _LOGGER if _LOGGER else getLogger(default_name)

harmony_regridding_service/regridding_cli.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from harmony_service_lib.message import Source as HarmonySource
66

7+
from harmony_regridding_service.log_context import set_logger
78
from harmony_regridding_service.message_utilities import get_harmony_message_from_params
89
from harmony_regridding_service.regridding_service import regrid
910

@@ -45,5 +46,7 @@ def regrid_cli_entry(
4546
call_logger: [Logger], a configured logging object.
4647
4748
"""
49+
if call_logger:
50+
set_logger(call_logger)
4851
harmony_message = get_harmony_message_from_params(params)
49-
return regrid(harmony_message, source_filename, HarmonySource(source), call_logger)
52+
return regrid(harmony_message, source_filename, HarmonySource(source))

harmony_regridding_service/regridding_service.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Regridding service code."""
22

3-
from logging import Logger, getLogger
3+
from logging import Logger, LoggerAdapter
44
from pathlib import Path
55

66
from harmony_service_lib.message import Message as HarmonyMessage
@@ -27,6 +27,7 @@
2727
transfer_metadata,
2828
)
2929
from harmony_regridding_service.grid import compute_target_areas
30+
from harmony_regridding_service.log_context import get_logger
3031
from harmony_regridding_service.resample import (
3132
cache_resamplers,
3233
copy_resampled_dimension_variables,
@@ -36,8 +37,6 @@
3637
)
3738
from harmony_regridding_service.var_utilitities import get_unprocessable_variables
3839

39-
logger = getLogger(__name__)
40-
4140

4241
def varinfo_config_filename() -> str:
4342
"""Return a path to the varinfo config."""
@@ -48,11 +47,10 @@ def regrid(
4847
message: HarmonyMessage,
4948
input_filepath: str,
5049
source: HarmonySource,
51-
call_logger: Logger,
50+
logger: Logger | LoggerAdapter | None = None,
5251
) -> str:
5352
"""Regrid the input data at input_filepath."""
54-
global logger
55-
logger = call_logger or logger
53+
logger = logger or get_logger()
5654
logger.info(f'Format:\n {message.format}')
5755
logger.info(f'Source:\n {source}')
5856

harmony_regridding_service/resample.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Module for resampling functions."""
22

3-
from logging import getLogger
43
from pathlib import PurePath
54

65
import numpy as np
@@ -35,8 +34,7 @@
3534
dims_are_lon_lat,
3635
dims_are_projected_x_y,
3736
)
38-
39-
logger = getLogger(__name__)
37+
from harmony_regridding_service.log_context import get_logger
4038

4139

4240
def resample_variable_data(
@@ -78,7 +76,7 @@ def resample_n_dimensional_variables(
7876
) -> set[str]:
7977
"""Function to resample any projected variable."""
8078
processed = set()
81-
79+
logger = get_logger()
8280
for var_name in variables:
8381
logger.debug(f'resampling {var_name}')
8482
try:
@@ -325,7 +323,7 @@ def cache_resamplers(
325323
"""
326324
grid_cache = {}
327325
for dim_pair in get_resampled_dimension_pairs(var_info):
328-
logger.debug(f'computing weights for dimensions {dim_pair}')
326+
get_logger().debug(f'computing weights for dimensions {dim_pair}')
329327
# create swath definitions for each grid in the source file.
330328
source_swath = compute_source_swath(dim_pair, filepath, var_info)
331329
grid_cache[dim_pair] = DaskEWAResampler(source_swath, target_areas[dim_pair])
@@ -416,7 +414,7 @@ def get_rows_per_scan(total_rows: int) -> int:
416414
if total_rows % row_number == 0:
417415
return row_number
418416

419-
logger.info(f'returning all rows for rows_per_scan = {total_rows}')
417+
get_logger().info(f'returning all rows for rows_per_scan = {total_rows}')
420418
return total_rows
421419

422420

@@ -468,7 +466,7 @@ def needs_rotation(var_info: VarInfoFromNetCDF4, variable: str) -> bool:
468466
None,
469467
)
470468
if row_loc > column_loc:
471-
logger.info(f'Incorrect dimension order on {variable}, needs rotation.')
469+
get_logger().info(f'Incorrect dimension order on {variable}, needs rotation.')
472470
variable_needs_rotation = True
473471

474472
return variable_needs_rotation

0 commit comments

Comments
 (0)