Skip to content

Commit d18d555

Browse files
Chris Elionvincentpierre
Chris Elion
authored andcommitted
Fix how we set logging levels (#3703)
* cleanup logging * comments and cleanup * pylint, gym
1 parent 47f11da commit d18d555

24 files changed

+110
-59
lines changed

.pylintrc

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,5 @@ disable =
4444
# Appears to be https://github.com/PyCQA/pylint/issues/2981
4545
W0201,
4646

47+
# Using the global statement
48+
W0603,

gym-unity/gym_unity/envs/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import logging
21
import itertools
32
import numpy as np
43
from typing import Any, Dict, List, Optional, Tuple, Union
@@ -8,6 +7,7 @@
87

98
from mlagents_envs.environment import UnityEnvironment
109
from mlagents_envs.base_env import BatchedStepResult
10+
from mlagents_envs import logging_util
1111

1212

1313
class UnityGymException(error.Error):
@@ -18,9 +18,8 @@ class UnityGymException(error.Error):
1818
pass
1919

2020

21-
logging.basicConfig(level=logging.INFO)
22-
logger = logging.getLogger("gym_unity")
23-
21+
logger = logging_util.get_logger(__name__)
22+
logging_util.set_log_level(logging_util.INFO)
2423

2524
GymSingleStepResult = Tuple[np.ndarray, float, bool, Dict]
2625
GymMultiStepResult = Tuple[List[np.ndarray], List[float], List[bool], Dict]

ml-agents-envs/mlagents_envs/environment.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import atexit
22
import glob
33
import uuid
4-
import logging
54
import numpy as np
65
import os
76
import subprocess
87
from typing import Dict, List, Optional, Any
98

109
import mlagents_envs
10+
11+
from mlagents_envs.logging_util import get_logger
1112
from mlagents_envs.side_channel.side_channel import SideChannel, IncomingMessage
1213

1314
from mlagents_envs.base_env import (
@@ -47,7 +48,7 @@
4748
import struct
4849

4950

50-
logger = logging.getLogger("mlagents_envs")
51+
logger = get_logger(__name__)
5152

5253

5354
class UnityEnvironment(BaseEnv):
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import logging # noqa I251
2+
3+
CRITICAL = logging.CRITICAL
4+
FATAL = logging.FATAL
5+
ERROR = logging.ERROR
6+
WARNING = logging.WARNING
7+
INFO = logging.INFO
8+
DEBUG = logging.DEBUG
9+
NOTSET = logging.NOTSET
10+
11+
_loggers = set()
12+
_log_level = NOTSET
13+
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
14+
LOG_FORMAT = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
15+
16+
17+
def get_logger(name: str) -> logging.Logger:
18+
"""
19+
Create a logger with the specified name. The logger will use the log level
20+
specified by set_log_level()
21+
"""
22+
logger = logging.getLogger(name=name)
23+
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)
27+
28+
# Keep track of this logger so that we can change the log level later
29+
_loggers.add(logger)
30+
return logger
31+
32+
33+
def set_log_level(log_level: int) -> None:
34+
"""
35+
Set the ML-Agents logging level. This will also configure the logging format (if it hasn't already been set).
36+
"""
37+
global _log_level
38+
_log_level = log_level
39+
40+
# Configure the log format.
41+
# In theory, this would be sufficient, but if another library calls logging.basicConfig
42+
# first, it doesn't have any effect.
43+
logging.basicConfig(level=_log_level, format=LOG_FORMAT, datefmt=DATE_FORMAT)
44+
45+
for logger in _loggers:
46+
logger.setLevel(log_level)

ml-agents-envs/mlagents_envs/side_channel/outgoing_message.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from typing import List
22
import struct
33

4-
import logging
4+
from mlagents_envs.logging_util import get_logger
55

6-
logger = logging.getLogger(__name__)
6+
logger = get_logger(__name__)
77

88

99
class OutgoingMessage:

ml-agents-envs/mlagents_envs/side_channel/side_channel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from abc import ABC, abstractmethod
22
from typing import List
33
import uuid
4-
import logging
54

65
from mlagents_envs.side_channel import IncomingMessage, OutgoingMessage
6+
from mlagents_envs.logging_util import get_logger
77

8-
logger = logging.getLogger(__name__)
8+
logger = get_logger(__name__)
99

1010

1111
class SideChannel(ABC):

ml-agents/mlagents/logging_util.py

Lines changed: 0 additions & 10 deletions
This file was deleted.

ml-agents/mlagents/model_serialization.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from distutils.util import strtobool
22
import os
3-
import logging
43
from typing import Any, List, Set, NamedTuple
54
from distutils.version import LooseVersion
65

@@ -19,14 +18,16 @@
1918

2019
from tensorflow.python.platform import gfile
2120
from tensorflow.python.framework import graph_util
21+
22+
from mlagents_envs.logging_util import get_logger
2223
from mlagents.trainers import tensorflow_to_barracuda as tf2bc
2324

2425
if LooseVersion(tf.__version__) < LooseVersion("1.12.0"):
2526
# ONNX is only tested on 1.12.0 and later
2627
ONNX_EXPORT_ENABLED = False
2728

29+
logger = get_logger(__name__)
2830

29-
logger = logging.getLogger("mlagents.trainers")
3031

3132
POSSIBLE_INPUT_NODES = frozenset(
3233
[

ml-agents/mlagents/trainers/components/reward_signals/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1-
import logging
21
from typing import Any, Dict, List
32
from collections import namedtuple
43
import numpy as np
54
import abc
65

76
from mlagents.tf_utils import tf
87

8+
from mlagents_envs.logging_util import get_logger
99
from mlagents.trainers.exception import UnityTrainerException
1010
from mlagents.trainers.policy.tf_policy import TFPolicy
1111
from mlagents.trainers.buffer import AgentBuffer
1212

13-
logger = logging.getLogger("mlagents.trainers")
13+
14+
logger = get_logger(__name__)
1415

1516
RewardSignalResult = namedtuple(
1617
"RewardSignalResult", ["scaled_reward", "unscaled_reward"]

ml-agents/mlagents/trainers/curriculum.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44

55
from .exception import CurriculumConfigError, CurriculumLoadingError
66

7-
import logging
7+
from mlagents_envs.logging_util import get_logger
88

9-
logger = logging.getLogger("mlagents.trainers")
9+
logger = get_logger(__name__)
1010

1111

1212
class Curriculum:

ml-agents/mlagents/trainers/env_manager.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
from abc import ABC, abstractmethod
2-
import logging
32
from typing import List, Dict, NamedTuple, Iterable
43
from mlagents_envs.base_env import BatchedStepResult, AgentGroupSpec, AgentGroup
54
from mlagents.trainers.brain import BrainParameters
65
from mlagents.trainers.policy.tf_policy import TFPolicy
76
from mlagents.trainers.agent_processor import AgentManager, AgentManagerQueue
87
from mlagents.trainers.action_info import ActionInfo
8+
from mlagents_envs.logging_util import get_logger
99

1010
AllStepResult = Dict[AgentGroup, BatchedStepResult]
1111
AllGroupSpec = Dict[AgentGroup, AgentGroupSpec]
1212

13-
logger = logging.getLogger("mlagents.trainers")
13+
14+
logger = get_logger(__name__)
1415

1516

1617
class EnvironmentStep(NamedTuple):

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
from typing import Deque, Dict, List, Any, cast
55

66
import numpy as np
7-
import logging
87

8+
from mlagents_envs.logging_util import get_logger
99
from mlagents.trainers.brain import BrainParameters
1010
from mlagents.trainers.policy import Policy
1111
from mlagents.trainers.policy.tf_policy import TFPolicy
@@ -14,7 +14,8 @@
1414
from mlagents.trainers.trajectory import Trajectory
1515
from mlagents.trainers.agent_processor import AgentManagerQueue
1616

17-
logger = logging.getLogger("mlagents.trainers")
17+
18+
logger = get_logger(__name__)
1819

1920

2021
class GhostTrainer(Trainer):

ml-agents/mlagents/trainers/learn.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# # Unity ML-Agents Toolkit
2-
import logging
32
import argparse
43

54
import os
@@ -31,7 +30,9 @@
3130
from mlagents_envs.side_channel.engine_configuration_channel import EngineConfig
3231
from mlagents_envs.exception import UnityEnvironmentException
3332
from mlagents_envs.timers import hierarchical_timer, get_timer_tree
34-
from mlagents.logging_util import create_logger
33+
from mlagents_envs import logging_util
34+
35+
logger = logging_util.get_logger(__name__)
3536

3637

3738
def _create_parser():
@@ -338,7 +339,7 @@ def write_timing_tree(summaries_dir: str, run_id: str) -> None:
338339
with open(timing_path, "w") as f:
339340
json.dump(get_timer_tree(), f, indent=4)
340341
except FileNotFoundError:
341-
logging.warning(
342+
logger.warning(
342343
f"Unable to save to {timing_path}. Make sure the directory exists"
343344
)
344345

@@ -395,7 +396,7 @@ def prepare_for_docker_run(docker_target_name, env_path):
395396
shutil.copyfile(src_f, dst_f)
396397
os.chmod(dst_f, 0o775) # Make executable
397398
except Exception as e:
398-
logging.getLogger("mlagents.trainers").info(e)
399+
logger.info(e)
399400
env_path = "/ml-agents/{env_path}".format(env_path=env_path)
400401
return env_path
401402

@@ -471,16 +472,16 @@ def run_cli(options: RunOptions) -> None:
471472
print(get_version_string())
472473

473474
if options.debug:
474-
log_level = logging.DEBUG
475+
log_level = logging_util.DEBUG
475476
else:
476-
log_level = logging.INFO
477+
log_level = logging_util.INFO
477478
# disable noisy warnings from tensorflow
478479
tf_utils.set_warnings_enabled(False)
479480

480-
trainer_logger = create_logger("mlagents.trainers", log_level)
481+
logging_util.set_log_level(log_level)
481482

482-
trainer_logger.debug("Configuration for this run:")
483-
trainer_logger.debug(json.dumps(options._asdict(), indent=4))
483+
logger.debug("Configuration for this run:")
484+
logger.debug(json.dumps(options._asdict(), indent=4))
484485

485486
run_seed = options.seed
486487
if options.cpu:

ml-agents/mlagents/trainers/meta_curriculum.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
from typing import Dict, Set
44
from mlagents.trainers.curriculum import Curriculum
55

6-
import logging
6+
from mlagents_envs.logging_util import get_logger
77

8-
logger = logging.getLogger("mlagents.trainers")
8+
logger = get_logger(__name__)
99

1010

1111
class MetaCurriculum:

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import logging
21
from typing import Any, Dict, List, Optional
32
import abc
43
import numpy as np
54
from mlagents.tf_utils import tf
65
from mlagents import tf_utils
76
from mlagents_envs.exception import UnityException
7+
from mlagents_envs.logging_util import get_logger
88
from mlagents.trainers.policy import Policy
99
from mlagents.trainers.action_info import ActionInfo
1010
from mlagents.trainers.trajectory import SplitObservations
@@ -13,7 +13,7 @@
1313
from mlagents.trainers.models import ModelUtils
1414

1515

16-
logger = logging.getLogger("mlagents.trainers")
16+
logger = get_logger(__name__)
1717

1818

1919
class UnityPolicyException(UnityException):

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
# ## ML-Agent Learning (PPO)
33
# Contains an implementation of PPO as described in: https://arxiv.org/abs/1707.06347
44

5-
import logging
65
from collections import defaultdict
76

87
import numpy as np
98

9+
from mlagents_envs.logging_util import get_logger
1010
from mlagents.trainers.policy.nn_policy import NNPolicy
1111
from mlagents.trainers.trainer.rl_trainer import RLTrainer
1212
from mlagents.trainers.brain import BrainParameters
@@ -16,7 +16,7 @@
1616
from mlagents.trainers.exception import UnityTrainerException
1717

1818

19-
logger = logging.getLogger("mlagents.trainers")
19+
logger = get_logger(__name__)
2020

2121

2222
class PPOTrainer(RLTrainer):

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import logging
21
import numpy as np
32
from typing import Dict, List, Optional, Any, Mapping
43

54
from mlagents.tf_utils import tf
65

6+
from mlagents_envs.logging_util import get_logger
77
from mlagents.trainers.sac.network import SACPolicyNetwork, SACTargetNetwork
88
from mlagents.trainers.models import LearningRateSchedule, EncoderType, ModelUtils
99
from mlagents.trainers.optimizer.tf_optimizer import TFOptimizer
@@ -13,7 +13,7 @@
1313

1414
EPSILON = 1e-6 # Small value to avoid divide by zero
1515

16-
logger = logging.getLogger("mlagents.trainers")
16+
logger = get_logger(__name__)
1717

1818
POLICY_SCOPE = ""
1919
TARGET_SCOPE = "target_network"

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
# Contains an implementation of SAC as described in https://arxiv.org/abs/1801.01290
33
# and implemented in https://github.com/hill-a/stable-baselines
44

5-
import logging
65
from collections import defaultdict
76
from typing import Dict
87
import os
98

109
import numpy as np
1110

1211

12+
from mlagents_envs.logging_util import get_logger
1313
from mlagents_envs.timers import timed
1414
from mlagents.trainers.policy.tf_policy import TFPolicy
1515
from mlagents.trainers.policy.nn_policy import NNPolicy
@@ -20,7 +20,8 @@
2020
from mlagents.trainers.exception import UnityTrainerException
2121

2222

23-
logger = logging.getLogger("mlagents.trainers")
23+
logger = get_logger(__name__)
24+
2425
BUFFER_TRUNCATE_PERCENT = 0.8
2526

2627

0 commit comments

Comments
 (0)