logger.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # Copyright (c) 2022 NVIDIA Corporation. 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 paddle.distributed as dist
  16. import dllogger
  17. def format_step(step):
  18. """
  19. Define prefix for different prefix message for dllogger.
  20. Args:
  21. step(str|tuple): Dllogger step format.
  22. Returns:
  23. s(str): String to print in log.
  24. """
  25. if isinstance(step, str):
  26. return step
  27. s = ""
  28. if len(step) > 0:
  29. s += f"Epoch: {step[0]} "
  30. if len(step) > 1:
  31. s += f"Iteration: {step[1]} "
  32. if len(step) > 2:
  33. s += f"Validation Iteration: {step[2]} "
  34. if len(step) == 0:
  35. s = "Summary:"
  36. return s
  37. def setup_dllogger(log_file):
  38. """
  39. Setup logging and dllogger.
  40. Args:
  41. log_file(str): Path to log file.
  42. """
  43. logging.basicConfig(
  44. level=logging.DEBUG,
  45. format='{asctime}:{levelname}: {message}',
  46. style='{')
  47. if dist.get_rank() == 0:
  48. dllogger.init(backends=[
  49. dllogger.StdOutBackend(
  50. dllogger.Verbosity.DEFAULT, step_format=format_step),
  51. dllogger.JSONStreamBackend(dllogger.Verbosity.VERBOSE, log_file),
  52. ])
  53. else:
  54. dllogger.init([])