logging.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. """
  15. This code is refer from:
  16. https://github.com/WenmuZhou/PytorchOCR/blob/master/torchocr/utils/logging.py
  17. """
  18. import os
  19. import sys
  20. import logging
  21. import functools
  22. import paddle.distributed as dist
  23. logger_initialized = {}
  24. @functools.lru_cache()
  25. def get_logger(name='ppocr', log_file=None, log_level=logging.DEBUG):
  26. """Initialize and get a logger by name.
  27. If the logger has not been initialized, this method will initialize the
  28. logger by adding one or two handlers, otherwise the initialized logger will
  29. be directly returned. During initialization, a StreamHandler will always be
  30. added. If `log_file` is specified a FileHandler will also be added.
  31. Args:
  32. name (str): Logger name.
  33. log_file (str | None): The log filename. If specified, a FileHandler
  34. will be added to the logger.
  35. log_level (int): The logger level. Note that only the process of
  36. rank 0 is affected, and other processes will set the level to
  37. "Error" thus be silent most of the time.
  38. Returns:
  39. logging.Logger: The expected logger.
  40. """
  41. logger = logging.getLogger(name)
  42. if name in logger_initialized:
  43. return logger
  44. for logger_name in logger_initialized:
  45. if name.startswith(logger_name):
  46. return logger
  47. formatter = logging.Formatter(
  48. '[%(asctime)s] %(name)s %(levelname)s: %(message)s',
  49. datefmt="%Y/%m/%d %H:%M:%S")
  50. stream_handler = logging.StreamHandler(stream=sys.stdout)
  51. stream_handler.setFormatter(formatter)
  52. logger.addHandler(stream_handler)
  53. if log_file is not None and dist.get_rank() == 0:
  54. log_file_folder = os.path.split(log_file)[0]
  55. os.makedirs(log_file_folder, exist_ok=True)
  56. file_handler = logging.FileHandler(log_file, 'a')
  57. file_handler.setFormatter(formatter)
  58. logger.addHandler(file_handler)
  59. if dist.get_rank() == 0:
  60. logger.setLevel(log_level)
  61. else:
  62. logger.setLevel(logging.ERROR)
  63. logger_initialized[name] = True
  64. logger.propagate = False
  65. return logger