logger.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #
  2. # Copyright 2019 The FATE Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import os
  17. import sys
  18. from pathlib import Path
  19. import loguru
  20. from pipeline.backend.config import LogPath, LogFormat, PipelineConfig
  21. RUNTIME_LOG = "runtime"
  22. info_log_path = os.path.join(LogPath.log_directory(), LogPath.INFO)
  23. debug_log_path = os.path.join(LogPath.log_directory(), LogPath.DEBUG)
  24. error_log_path = os.path.join(LogPath.log_directory(), LogPath.ERROR)
  25. def runtime_log_only(record):
  26. log_type = record["extra"].get("log_type", "")
  27. return log_type == RUNTIME_LOG
  28. LOGGER = loguru.logger
  29. LOGGER.remove()
  30. LOGGER.configure(extra={"format": LogFormat.NORMAL})
  31. if PipelineConfig.CONSOLE_DISPLAY_LOG:
  32. console_handler = LOGGER.add(sys.stderr, level="INFO", colorize=True,
  33. filter=runtime_log_only)
  34. LOGGER.add(Path(info_log_path).resolve(), level="INFO", rotation="500MB",
  35. colorize=True, filter=runtime_log_only)
  36. LOGGER.add(Path(debug_log_path).resolve(), level="DEBUG", rotation="500MB", colorize=True,
  37. filter=runtime_log_only)
  38. LOGGER.add(Path(error_log_path).resolve(), level="ERROR", rotation="500MB", colorize=True,
  39. backtrace=True, filter=runtime_log_only)
  40. LOGGER = LOGGER.bind(log_type=RUNTIME_LOG)
  41. def disable_console_log():
  42. """
  43. disable logging to stderr, for silent mode
  44. Returns
  45. -------
  46. """
  47. try:
  48. LOGGER.remove(console_handler)
  49. except BaseException:
  50. pass
  51. def enable_console_log():
  52. disable_console_log()
  53. global console_handler
  54. console_handler = LOGGER.add(sys.stderr, level="INFO", colorize=True,
  55. filter=runtime_log_only)