1# Copyright 2022 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14"""The module contains helpers to initialize and configure logging.""" 15import functools 16import pathlib 17 18from absl import flags 19from absl import logging 20 21 22def _ensure_flags_parsed() -> None: 23 if not flags.FLAGS.is_parsed(): 24 raise flags.UnparsedFlagAccessError('Must initialize absl flags first.') 25 26 27@functools.lru_cache(None) 28def log_get_root_dir() -> pathlib.Path: 29 _ensure_flags_parsed() 30 log_root = pathlib.Path(logging.find_log_dir()).absolute() 31 logging.info("Log root dir: %s", log_root) 32 return log_root 33 34 35def log_dir_mkdir(name: str) -> pathlib.Path: 36 """Creates and returns a subdir with the given name in the log folder.""" 37 if len(pathlib.Path(name).parts) != 1: 38 raise ValueError(f'Dir name must be a single component; got: {name}') 39 if ".." in name: 40 raise ValueError(f'Dir name must not be above the log root.') 41 log_subdir = log_get_root_dir() / name 42 if log_subdir.exists() and log_subdir.is_dir(): 43 logging.debug("Using existing log subdir: %s", log_subdir) 44 else: 45 log_subdir.mkdir() 46 logging.debug("Created log subdir: %s", log_subdir) 47 48 return log_subdir 49