log.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # !/usr/bin/env python3
  2. # -*- coding: UTF-8 -*-
  3. ################################################################################
  4. #
  5. # Copyright (c) 2023 Baidu.com, Inc. All Rights Reserved
  6. #
  7. ################################################################################
  8. """
  9. 本文件实现了sdk日志的功能
  10. Authors: xiangyiqing(xiangyiqing@baidu.com)
  11. Date: 2023/07/24
  12. """
  13. import os
  14. import logging
  15. from aistudio_sdk import config
  16. from aistudio_sdk.constant.const import LOG_LEVEL_FILE
  17. __all__ = [
  18. "info",
  19. "debug",
  20. "warn",
  21. "error",
  22. "get_level",
  23. ]
  24. def get_level():
  25. """
  26. 三种设置日志级别的方式,优先级从高到低:
  27. 1、执行前, 设置环境变量 AISTUDIO_LOG 的值
  28. 2、执行前, 设置level值到文件 ${AISTUDIO_CACHE_HOME}/.cache/aistudio/.log/level
  29. 3、执行前, 设置config文件中DEFAULT_LOG_LEVEL的值
  30. """
  31. if "AISTUDIO_LOG" in os.environ:
  32. return os.getenv("AISTUDIO_LOG")
  33. if os.path.exists(LOG_LEVEL_FILE):
  34. try:
  35. with open(LOG_LEVEL_FILE, 'r') as file:
  36. return file.read().strip()
  37. except:
  38. pass
  39. return config.DEFAULT_LOG_LEVEL
  40. # 初始化
  41. logger = logging.getLogger("aistudio_sdk")
  42. level = get_level()
  43. if level == "debug":
  44. logger.setLevel(logging.DEBUG)
  45. elif level == 'critical':
  46. logger.setLevel(logging.CRITICAL)
  47. else:
  48. logger.setLevel(logging.INFO)
  49. # 日志输出格式
  50. formatter = logging.Formatter(fmt='%(levelname)-8s %(asctime)s %(process)-5s %(filename)s[line:%(lineno)d] %(message)s')
  51. # 控制台输出
  52. console_handler = logging.StreamHandler()
  53. console_handler.setFormatter(formatter)
  54. logger.addHandler(console_handler)
  55. def cli_log():
  56. """
  57. cli log格式沿用原有的
  58. """
  59. console_handler.setFormatter(logging.Formatter(fmt='%(message)s'))
  60. def info(msg):
  61. """log evel: INFO"""
  62. logger.log(logging.INFO, msg)
  63. def debug(msg):
  64. """log evel: DEBUG"""
  65. logger.log(logging.DEBUG, f"[DEBUG] {msg}")
  66. def warn(msg):
  67. """log evel: WARN"""
  68. logger.log(logging.WARN, msg)
  69. def error(msg):
  70. """log evel: ERROR"""
  71. logger.log(logging.ERROR, msg)