Skip to content

Commit c0889d5

Browse files
Turning some logger.info into logger.debug and remove some logging overhead when not using debug (#5211)
* turning some logger.info into logger.debug and remove some logging overhead when not using debug * Addressing comments * Adding to changelog
1 parent 82464ac commit c0889d5

File tree

11 files changed

+38
-19
lines changed

11 files changed

+38
-19
lines changed

com.unity.ml-agents/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ depend on the previous behavior, you can explicitly set the Agent's `InferenceDe
4343
- Modified the [GridWorld environment](https://github.com/Unity-Technologies/ml-agents/blob/main/docs/Learning-Environment-Examples.md#gridworld) to use the new `Goal Signal` feature. (#5193)
4444

4545
#### ml-agents / ml-agents-envs / gym-unity (Python)
46+
- Some console output have been moved from `info` to `debug` and will not be printed by default. If you want all messages to be printed, you can run `mlagents-learn` with the `--debug` option or add the line `debug: true` at the top of the yaml config file. (#5211)
4647

4748
### Bug Fixes
4849
#### com.unity.ml-agents / com.unity.ml-agents.extensions (C#)

ml-agents-envs/mlagents_envs/environment.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -279,7 +279,7 @@ def _update_behavior_specs(self, output: UnityOutputProto) -> None:
279279
agent = agent_infos.value[0]
280280
new_spec = behavior_spec_from_proto(brain_param, agent)
281281
self._env_specs[brain_param.brain_name] = new_spec
282-
logger.info(f"Connected new brain:\n{brain_param.brain_name}")
282+
logger.info(f"Connected new brain: {brain_param.brain_name}")
283283

284284
def _update_state(self, output: UnityRLOutputProto) -> None:
285285
"""
@@ -426,9 +426,9 @@ def _close(self, timeout: Optional[int] = None) -> None:
426426
# Wait a bit for the process to shutdown, but kill it if it takes too long
427427
try:
428428
self._process.wait(timeout=timeout)
429-
logger.info(self._returncode_to_env_message(self._process.returncode))
429+
logger.debug(self._returncode_to_env_message(self._process.returncode))
430430
except subprocess.TimeoutExpired:
431-
logger.info("Environment timed out shutting down. Killing...")
431+
logger.warning("Environment timed out shutting down. Killing...")
432432
self._process.kill()
433433
# Set to None so we don't try to close multiple times.
434434
self._process = None

ml-agents-envs/mlagents_envs/logging_util.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
_loggers = set()
1313
_log_level = NOTSET
1414
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
15-
LOG_FORMAT = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
15+
DEBUG_LOG_FORMAT = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
16+
LOG_FORMAT = "[%(levelname)s] %(message)s"
1617

1718

1819
def get_logger(name: str) -> logging.Logger:
@@ -21,15 +22,19 @@ def get_logger(name: str) -> logging.Logger:
2122
specified by set_log_level()
2223
"""
2324
logger = logging.getLogger(name=name)
24-
# If we've already set the log level, make sure new loggers use it
25-
if _log_level != NOTSET:
26-
logger.setLevel(_log_level)
2725

26+
if _log_level == DEBUG:
27+
formatter = logging.Formatter(fmt=DEBUG_LOG_FORMAT, datefmt=DATE_FORMAT)
28+
else:
29+
formatter = logging.Formatter(fmt=LOG_FORMAT)
2830
handler = logging.StreamHandler(stream=sys.stdout)
29-
formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT)
3031
handler.setFormatter(formatter)
3132
logger.addHandler(handler)
3233

34+
# If we've already set the log level, make sure new loggers use it
35+
if _log_level != NOTSET:
36+
logger.setLevel(_log_level)
37+
3338
# Keep track of this logger so that we can change the log level later
3439
_loggers.add(logger)
3540
return logger
@@ -44,3 +49,15 @@ def set_log_level(log_level: int) -> None:
4449

4550
for logger in _loggers:
4651
logger.setLevel(log_level)
52+
53+
if log_level == DEBUG:
54+
formatter = logging.Formatter(fmt=DEBUG_LOG_FORMAT, datefmt=DATE_FORMAT)
55+
else:
56+
formatter = logging.Formatter(LOG_FORMAT)
57+
_set_formatter_for_all_loggers(formatter)
58+
59+
60+
def _set_formatter_for_all_loggers(formatter: logging.Formatter) -> None:
61+
for logger in _loggers:
62+
for handler in logger.handlers[:]:
63+
handler.setFormatter(formatter)

ml-agents/mlagents/torch_utils/torch.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def set_torch_config(torch_settings: TorchSettings) -> None:
5555
torch.set_default_tensor_type(torch.cuda.FloatTensor)
5656
else:
5757
torch.set_default_tensor_type(torch.FloatTensor)
58-
logger.info(f"default Torch device: {_device}")
58+
logger.debug(f"default Torch device: {_device}")
5959

6060

6161
# Initialize to default settings

ml-agents/mlagents/trainers/learn.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def run_cli(options: RunOptions) -> None:
242242

243243
if options.env_settings.seed == -1:
244244
run_seed = np.random.randint(0, 10000)
245-
logger.info(f"run_seed set to {run_seed}")
245+
logger.debug(f"run_seed set to {run_seed}")
246246
run_training(run_seed, options)
247247

248248

ml-agents/mlagents/trainers/policy/checkpoint_manager.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ def remove_checkpoint(checkpoint: Dict[str, Any]) -> None:
4040
file_path: str = checkpoint["file_path"]
4141
if os.path.exists(file_path):
4242
os.remove(file_path)
43-
logger.info(f"Removed checkpoint model {file_path}.")
43+
logger.debug(f"Removed checkpoint model {file_path}.")
4444
else:
45-
logger.info(f"Checkpoint at {file_path} could not be found.")
45+
logger.debug(f"Checkpoint at {file_path} could not be found.")
4646
return
4747

4848
@classmethod

ml-agents/mlagents/trainers/sac/trainer.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,10 +116,10 @@ def load_replay_buffer(self) -> None:
116116
Loads the last saved replay buffer from a file.
117117
"""
118118
filename = os.path.join(self.artifact_path, "last_replay_buffer.hdf5")
119-
logger.info(f"Loading Experience Replay Buffer from {filename}")
119+
logger.info(f"Loading Experience Replay Buffer from {filename}...")
120120
with open(filename, "rb+") as file_object:
121121
self.update_buffer.load_from_file(file_object)
122-
logger.info(
122+
logger.debug(
123123
"Experience replay buffer has {} experiences.".format(
124124
self.update_buffer.num_experiences
125125
)

ml-agents/mlagents/trainers/stats.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,13 +235,14 @@ def _delete_all_events_files(self, directory_name: str) -> None:
235235
for file_name in os.listdir(directory_name):
236236
if file_name.startswith("events.out"):
237237
logger.warning(
238-
f"{file_name} was left over from a previous run. Deleting."
238+
f"Deleting TensorBoard data {file_name} that was left over from a"
239+
"previous run."
239240
)
240241
full_fname = os.path.join(directory_name, file_name)
241242
try:
242243
os.remove(full_fname)
243244
except OSError:
244-
logger.warning(
245+
logger.error(
245246
"{} was left over from a previous run and "
246247
"not deleted.".format(full_fname)
247248
)

ml-agents/mlagents/trainers/subprocess_env_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ def _generate_all_results() -> AllStepResult:
217217
UnityEnvironmentException,
218218
UnityCommunicatorStoppedException,
219219
) as ex:
220-
logger.info(f"UnityEnvironment worker {worker_id}: environment stopping.")
220+
logger.debug(f"UnityEnvironment worker {worker_id}: environment stopping.")
221221
step_queue.put(
222222
EnvironmentResponse(EnvironmentCommand.ENV_EXITED, worker_id, ex)
223223
)

ml-agents/mlagents/trainers/torch/model_serialization.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ def export_policy_model(self, output_filepath: str) -> None:
153153
:param output_filepath: file path to output the model (without file suffix)
154154
"""
155155
onnx_output_path = f"{output_filepath}.onnx"
156-
logger.info(f"Converting to {onnx_output_path}")
156+
logger.debug(f"Converting to {onnx_output_path}")
157157

158158
with exporting_to_onnx():
159159
torch.onnx.export(

ml-agents/mlagents/trainers/trainer_controller.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def _save_models(self):
7878

7979
for brain_name in self.trainers.keys():
8080
self.trainers[brain_name].save_model()
81-
self.logger.info("Saved Model")
81+
self.logger.debug("Saved Model")
8282

8383
@staticmethod
8484
def _create_output_path(output_path):

0 commit comments

Comments
 (0)