Skip to content

Commit aff7bc1

Browse files
authored
improve: enable logging for multiprocessing (#774)
* use LOG.isEnabledFor(DEBUG) * configure logger in multiprocessing * fix comments * fix types * use ProcessPoolExecutor * imports * fix mp_map
1 parent c9e4a97 commit aff7bc1

File tree

13 files changed

+73
-33
lines changed

13 files changed

+73
-33
lines changed

mapillary_tools/commands/__main__.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from .. import api_v4, constants, exceptions, VERSION
1010
from ..upload import log_exception
11+
from ..utils import configure_logger, get_app_name
1112
from . import (
1213
authenticate,
1314
process,
@@ -31,8 +32,8 @@
3132
]
3233

3334

34-
# do not use __name__ here is because if you run tools as a module, __name__ will be "__main__"
35-
LOG = logging.getLogger("mapillary_tools")
35+
# Root logger of mapillary_tools (not including third-party libraries)
36+
LOG = logging.getLogger(get_app_name())
3637

3738

3839
# Handle shared arguments/options here
@@ -79,13 +80,6 @@ def add_general_arguments(parser, command):
7980
)
8081

8182

82-
def configure_logger(logger: logging.Logger, stream=None) -> None:
83-
formatter = logging.Formatter("%(asctime)s - %(levelname)-7s - %(message)s")
84-
handler = logging.StreamHandler(stream)
85-
handler.setFormatter(formatter)
86-
logger.addHandler(handler)
87-
88-
8983
def _log_params(argvars: dict) -> None:
9084
MAX_ENTRIES = 5
9185

@@ -152,9 +146,7 @@ def main():
152146

153147
args = parser.parse_args()
154148

155-
log_level = logging.DEBUG if args.verbose else logging.INFO
156-
configure_logger(LOG, sys.stderr)
157-
LOG.setLevel(log_level)
149+
configure_logger(LOG, level=logging.DEBUG if args.verbose else logging.INFO)
158150

159151
LOG.debug("%s", version_text)
160152
argvars = vars(args)

mapillary_tools/exif_read.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -871,7 +871,8 @@ def __init__(self, path_or_stream: Path | T.BinaryIO) -> None:
871871

872872
def _xmp_with_reason(self, reason: str) -> ExifReadFromXMP | None:
873873
if not self._xml_extracted:
874-
LOG.debug('Extracting XMP for "%s"', reason)
874+
# TODO Disabled because too verbose but still useful to know
875+
# LOG.debug('Extracting XMP for "%s"', reason)
875876
self._cached_xml = self._extract_xmp()
876877
self._xml_extracted = True
877878

mapillary_tools/geotag/base.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def to_description(
4646
map_results,
4747
desc="Extracting images",
4848
unit="images",
49-
disable=LOG.getEffectiveLevel() <= logging.DEBUG,
49+
disable=LOG.isEnabledFor(logging.DEBUG),
5050
total=len(extractors),
5151
)
5252
)
@@ -62,6 +62,8 @@ def run_extraction(cls, extractor: TImageExtractor) -> types.ImageMetadataOrErro
6262
try:
6363
return extractor.extract()
6464
except exceptions.MapillaryDescriptionError as ex:
65+
if LOG.isEnabledFor(logging.DEBUG):
66+
LOG.error(f"{cls.__name__}({image_path.name}): {ex}")
6567
return types.describe_error_metadata(
6668
ex, image_path, filetype=types.FileType.IMAGE
6769
)
@@ -112,7 +114,7 @@ def to_description(
112114
map_results,
113115
desc="Extracting videos",
114116
unit="videos",
115-
disable=LOG.getEffectiveLevel() <= logging.DEBUG,
117+
disable=LOG.isEnabledFor(logging.DEBUG),
116118
total=len(extractors),
117119
)
118120
)
@@ -128,6 +130,8 @@ def run_extraction(cls, extractor: TVideoExtractor) -> types.VideoMetadataOrErro
128130
try:
129131
return extractor.extract()
130132
except exceptions.MapillaryDescriptionError as ex:
133+
if LOG.isEnabledFor(logging.DEBUG):
134+
LOG.error(f"{cls.__name__}({video_path.name}): {ex}")
131135
return types.describe_error_metadata(
132136
ex, video_path, filetype=types.FileType.VIDEO
133137
)

mapillary_tools/geotag/factory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def process(
6767
reprocessable_paths = set(paths)
6868

6969
for idx, option in enumerate(options):
70-
if LOG.getEffectiveLevel() <= logging.DEBUG:
70+
if LOG.isEnabledFor(logging.DEBUG):
7171
LOG.info(
7272
f"==> Processing {len(reprocessable_paths)} files with source {option}..."
7373
)

mapillary_tools/geotag/geotag_images_from_exiftool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def _generate_image_extractors(
9393
LOG.warning(
9494
"Failed to parse ExifTool XML: %s",
9595
str(ex),
96-
exc_info=LOG.getEffectiveLevel() <= logging.DEBUG,
96+
exc_info=LOG.isEnabledFor(logging.DEBUG),
9797
)
9898
rdf_by_path = {}
9999
else:

mapillary_tools/geotag/geotag_videos_from_exiftool.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def _generate_video_extractors(
110110
LOG.warning(
111111
"Failed to parse ExifTool XML: %s",
112112
str(ex),
113-
exc_info=LOG.getEffectiveLevel() <= logging.DEBUG,
113+
exc_info=LOG.isEnabledFor(logging.DEBUG),
114114
)
115115
rdf_by_path = {}
116116
else:

mapillary_tools/geotag/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def index_rdf_description_by_path(
4646
try:
4747
etree = ET.parse(xml_path)
4848
except ET.ParseError as ex:
49-
verbose = LOG.getEffectiveLevel() <= logging.DEBUG
49+
verbose = LOG.isEnabledFor(logging.DEBUG)
5050
if verbose:
5151
LOG.warning("Failed to parse %s", xml_path, exc_info=True)
5252
else:

mapillary_tools/http.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def _log_debug_request(self, method: str | bytes, url: str | bytes, **kwargs):
8888
if self.disable_logging_request:
8989
return
9090

91-
if logging.getLogger().getEffectiveLevel() <= logging.DEBUG:
91+
if not LOG.isEnabledFor(logging.DEBUG):
9292
return
9393

9494
if isinstance(method, str) and isinstance(url, str):
@@ -124,7 +124,7 @@ def _log_debug_response(self, resp: requests.Response):
124124
if self.disable_logging_response:
125125
return
126126

127-
if logging.getLogger().getEffectiveLevel() <= logging.DEBUG:
127+
if not LOG.isEnabledFor(logging.DEBUG):
128128
return
129129

130130
elapsed = resp.elapsed.total_seconds() * 1000 # Convert to milliseconds

mapillary_tools/process_geotag_properties.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def _overwrite_exif_tags(
167167
metadatas,
168168
desc="Overwriting EXIF",
169169
unit="images",
170-
disable=LOG.getEffectiveLevel() <= logging.DEBUG,
170+
disable=LOG.isEnabledFor(logging.DEBUG),
171171
):
172172
dt = datetime.datetime.fromtimestamp(metadata.time, datetime.timezone.utc)
173173
dt = dt.replace(tzinfo=datetime.timezone.utc)

mapillary_tools/sample_video.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,12 +125,11 @@ def sample_video(
125125

126126
except Exception as ex:
127127
if skip_sample_errors:
128-
exc_info = LOG.getEffectiveLevel() <= logging.DEBUG
129128
LOG.warning(
130129
"Skipping the error sampling %s: %s",
131130
video_path,
132131
str(ex),
133-
exc_info=exc_info,
132+
exc_info=LOG.isEnabledFor(logging.DEBUG),
134133
)
135134
else:
136135
raise

0 commit comments

Comments
 (0)