Skip to content

Commit 9554718

Browse files
markbaderfm3
andauthored
Replace logging.info with a logger for each file (#1335)
* replace logging.info with a logger for each file. * Update changelog. * Update webknossos/Changelog.md Co-authored-by: Florian M <[email protected]> --------- Co-authored-by: Florian M <[email protected]>
1 parent 53d32d8 commit 9554718

File tree

13 files changed

+51
-38
lines changed

13 files changed

+51
-38
lines changed

webknossos/Changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ For upgrade instructions, please check the respective _Breaking Changes_ section
1717
### Added
1818

1919
### Changed
20+
- Every file that sends logging messages has its own logger now. This can be used to selectively disable loggers. [#1335](https://github.com/scalableminds/webknossos-libs/pull/1335)
2021

2122
### Fixed
2223

webknossos/webknossos/annotation/annotation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ def merge_fallback_layer(
774774
fallback_layer_name = volume_layer.fallback_layer_name
775775

776776
if fallback_layer_name is None:
777-
logging.info("No fallback layer found, save annotation as dataset.")
777+
logger.info("No fallback layer found, save annotation as dataset.")
778778
self.export_volume_layer_to_dataset(output_dataset)
779779

780780
else:
@@ -833,9 +833,9 @@ def merge_fallback_layer(
833833

834834
output_mag.merge_with_view(input_annotation_mag, executor)
835835

836-
logging.info("Delete temporary annotation layer")
836+
logger.info("Delete temporary annotation layer")
837837
output_dataset.delete_layer(tmp_annotation_layer_name)
838-
logging.info("Done.")
838+
logger.info("Done.")
839839

840840
def upload(self) -> str:
841841
"""Uploads the annotation to WEBKNOSSOS.

webknossos/webknossos/cli/check_equality.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def compare_layers(
116116
"""Compares one layer with another layer"""
117117

118118
layer_name = source_layer.name
119-
logging.info("Checking layer_name: %s", layer_name)
119+
logger.info("Checking layer_name: %s", layer_name)
120120

121121
assert source_layer.bounding_box == target_layer.bounding_box, (
122122
f"The bounding boxes of '{layer_name}' layer of source and target \
@@ -135,7 +135,7 @@ def compare_layers(
135135
source_mag = source_layer.mags[mag]
136136
target_mag = target_layer.mags[mag]
137137

138-
logging.info("Start verification of %s in mag %s", layer_name, mag)
138+
logger.info("Start verification of %s in mag %s", layer_name, mag)
139139
with get_executor_for_args(args=executor_args) as executor:
140140
assert source_mag.content_is_equal(target_mag, executor=executor), (
141141
f"The contents of {source_mag} and {target_mag} differ."

webknossos/webknossos/cli/convert_raw.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def _raw_chunk_converter(
5050
order: Literal["C", "F"],
5151
flip_axes: int | tuple[int, ...] | None,
5252
) -> None:
53-
logging.info("Conversion of %s", bounding_box.topleft)
53+
logger.info("Conversion of %s", bounding_box.topleft)
5454
source_data: np.ndarray = np.memmap(
5555
source_raw_path,
5656
dtype=np.dtype(input_dtype),

webknossos/webknossos/cli/convert_zarr.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def _zarr_chunk_converter(
5454
target_mag_view: MagView,
5555
flip_axes: int | tuple[int, ...] | None,
5656
) -> int:
57-
logging.info("Conversion of %s", bounding_box.topleft)
57+
logger.info("Conversion of %s", bounding_box.topleft)
5858

5959
slices = bounding_box.to_slices()
6060
zarr_file = _try_open_zarr(source_zarr_path)

webknossos/webknossos/cli/export_as_tiff.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
parse_vec2int,
2727
)
2828

29+
logger = logging.getLogger(__name__)
30+
2931

3032
def _make_tiff_name(name: str, slice_index: int) -> str:
3133
if name is None or name == "":
@@ -96,7 +98,7 @@ def export_tiff_slice(
9698

9799
image = _slice_to_image(tiff_data[:, :, :, slice_index], downsample)
98100
image.save(tiff_file_path)
99-
logging.debug("Saved slice %s", slice_name_number)
101+
logger.debug("Saved slice %s", slice_name_number)
100102

101103
else:
102104
for y_tile_index in range(ceil(tiff_bbox.size.y / tiling_size[1])):
@@ -120,9 +122,9 @@ def export_tiff_slice(
120122

121123
tile_image.save(tile_tiff_path / tile_tiff_filename)
122124

123-
logging.debug("Saved tiles for slice %s", slice_name_number)
125+
logger.debug("Saved tiles for slice %s", slice_name_number)
124126

125-
logging.debug("Saved all tiles of bbox %s", tiff_bbox)
127+
logger.debug("Saved all tiles of bbox %s", tiff_bbox)
126128

127129

128130
def export_tiff_stack(
@@ -264,7 +266,7 @@ def main(
264266
bbox = BoundingBox.from_ndbbox(mag_view.bounding_box) if bbox is None else bbox
265267
bbox = bbox.align_with_mag(mag_view.mag)
266268

267-
logging.info("Starting tiff export for bounding box: %s", bbox)
269+
logger.info("Starting tiff export for bounding box: %s", bbox)
268270
executor_args = Namespace(
269271
jobs=jobs,
270272
distribution_strategy=distribution_strategy.value,
@@ -273,7 +275,7 @@ def main(
273275
used_tile_size = None
274276
if tiles_per_dimension is not None:
275277
tile_size = tiles_per_dimension
276-
logging.info(
278+
logger.info(
277279
"Using tiling with %d,%d tiles in the dimensions.",
278280
tile_size[0],
279281
tile_size[1],
@@ -284,7 +286,7 @@ def main(
284286
)
285287

286288
elif tile_size is not None:
287-
logging.info("Using tiling with the size of %d,%d.", tile_size[0], tile_size[1])
289+
logger.info("Using tiling with the size of %d,%d.", tile_size[0], tile_size[1])
288290
used_tile_size = tile_size
289291

290292
export_tiff_stack(

webknossos/webknossos/dataset/_downsampling_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
from .layer_categories import LayerCategoryType
1818
from .view import View
1919

20+
logger = logging.getLogger(__name__)
21+
2022

2123
class InterpolationModes(Enum):
2224
MEDIAN = 0
@@ -367,7 +369,7 @@ def downsample_cube_job(
367369
target_view.write(file_buffer, absolute_bounding_box=target_view.bounding_box)
368370

369371
except Exception as exc:
370-
logging.error(
372+
logger.error(
371373
f"Downsampling of target {target_view.bounding_box} failed with {exc}"
372374
)
373375
raise exc

webknossos/webknossos/dataset/_upsampling_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
from .data_format import DataFormat
77
from .view import View
88

9+
logger = logging.getLogger(__name__)
10+
911

1012
def upsample_cube(cube_buffer: np.ndarray, factors: list[int]) -> np.ndarray:
1113
ds = cube_buffer.shape
@@ -69,7 +71,7 @@ def upsample_cube_job(
6971
target_view.write(file_buffer, absolute_bounding_box=chunk)
7072

7173
except Exception as exc:
72-
logging.error(
74+
logger.error(
7375
f"Upsampling of target {target_view.bounding_box} failed with {exc}"
7476
)
7577
raise exc

webknossos/webknossos/dataset/_utils/buffered_slice_reader.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1+
import logging
12
from collections.abc import Generator
2-
from logging import info
33
from os import getpid
44
from types import TracebackType
55
from typing import TYPE_CHECKING
@@ -11,6 +11,8 @@
1111

1212
from ...geometry import NDBoundingBox
1313

14+
logger = logging.getLogger(__name__)
15+
1416

1517
class BufferedSliceReader:
1618
def __init__(
@@ -50,7 +52,7 @@ def _get_slice_generator(self) -> Generator[np.ndarray, None, None]:
5052

5153
for chunk in self.bbox_current_mag.chunk(chunk_size):
5254
if self.use_logging:
53-
info(f"({getpid()}) Reading data from bbox {chunk}.")
55+
logger.info(f"({getpid()}) Reading data from bbox {chunk}.")
5456
data = self.view.read(
5557
absolute_bounding_box=chunk.from_mag_to_mag1(self.view.mag)
5658
)

webknossos/webknossos/dataset/_utils/buffered_slice_writer.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import logging
12
import os
23
import traceback
34
import warnings
45
from collections.abc import Generator
5-
from logging import error, info
66
from os import getpid
77
from types import TracebackType
88
from typing import TYPE_CHECKING
@@ -16,10 +16,13 @@
1616
from ..view import View
1717

1818

19+
logger = logging.getLogger(__name__)
20+
21+
1922
def log_memory_consumption(additional_output: str = "") -> None:
2023
pid = os.getpid()
2124
process = psutil.Process(pid)
22-
info(
25+
logger.info(
2326
f"Currently consuming {process.memory_info().rss / 1024**3:.2f} GB of memory ({psutil.virtual_memory().available / 1024**3:.2f} GB still available) "
2427
f"in process {pid}. {additional_output}"
2528
)
@@ -105,7 +108,7 @@ def _flush_buffer(self) -> None:
105108
)
106109

107110
if self._use_logging:
108-
info(
111+
logger.info(
109112
f"({getpid()}) Writing {len(self._slices_to_write)} slices at position {self._buffer_start_slice}."
110113
)
111114
log_memory_consumption()
@@ -136,7 +139,7 @@ def _flush_buffer(self) -> None:
136139
).moveaxis(-1, self.dimension)
137140
for chunk_bbox in bbox.chunk(chunk_size):
138141
if self._use_logging:
139-
info(f"Writing chunk {chunk_bbox}.")
142+
logger.info(f"Writing chunk {chunk_bbox}.")
140143

141144
data = np.zeros(
142145
(channel_count, *chunk_bbox.size),
@@ -199,12 +202,12 @@ def _flush_buffer(self) -> None:
199202
del data
200203

201204
except Exception as exc:
202-
error(
205+
logger.error(
203206
f"({getpid()}) An exception occurred in BufferedSliceWriter._flush_buffer with {len(self._slices_to_write)} "
204207
f"slices at position {self._buffer_start_slice}. Original error is:\n{type(exc).__name__}:{exc}\n\nTraceback:"
205208
)
206209
traceback.print_tb(exc.__traceback__)
207-
error("\n")
210+
logger.error("\n")
208211

209212
raise exc
210213
finally:

0 commit comments

Comments
 (0)