logger.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. import logging
  15. import os
  16. import sys
  17. __all__ = []
  18. def setup_logger(output=None, name="hapi", log_level=logging.INFO):
  19. """
  20. Initialize logger of hapi and set its verbosity level to "INFO".
  21. Args:
  22. output (str): a file name or a directory to save log. If None, will not save log file.
  23. If ends with ".txt" or ".log", assumed to be a file name.
  24. Otherwise, logs will be saved to `output/log.txt`.
  25. name (str): the root module name of this logger. Default: 'hapi'.
  26. log_level (enum): log level. eg.'INFO', 'DEBUG', 'ERROR'. Default: logging.INFO.
  27. Returns:
  28. logging.Logger: a logger
  29. """
  30. logger = logging.getLogger(name)
  31. logger.propagate = False
  32. logger.setLevel(log_level)
  33. format_str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  34. # stdout logging: only local rank==0
  35. local_rank = int(os.getenv("PADDLE_TRAINER_ID", "0"))
  36. if local_rank == 0 and len(logger.handlers) == 0:
  37. ch = logging.StreamHandler(stream=sys.stdout)
  38. ch.setLevel(log_level)
  39. ch.setFormatter(logging.Formatter(format_str))
  40. logger.addHandler(ch)
  41. # file logging if output is not None: all workers
  42. if output is not None:
  43. if output.endswith(".txt") or output.endswith(".log"):
  44. filename = output
  45. else:
  46. filename = os.path.join(output, "log.txt")
  47. if local_rank > 0:
  48. filename = filename + f".rank{local_rank}"
  49. if not os.path.exists(os.path.dirname(filename)):
  50. os.makedirs(os.path.dirname(filename))
  51. fh = logging.StreamHandler(filename)
  52. fh.setLevel(log_level)
  53. fh.setFormatter(logging.Formatter(format_str))
  54. logger.addHandler(fh)
  55. return logger