log.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2021/6/7 11:02
  3. # @Author : XuJiakai
  4. # @File : log
  5. # @Software: PyCharm
  6. import logging
  7. import os
  8. import time
  9. import platform
  10. AUTO_WRITE_LOG_FILE = False if platform.system() == "Linux" else True
  11. AUTO_WRITE_LOG_FILE = False
  12. def get_log(log_name="my_log", write_file=AUTO_WRITE_LOG_FILE):
  13. logging.basicConfig()
  14. logger = logging.getLogger(log_name)
  15. logger.setLevel(logging.WARNING)
  16. # logger.setLevel(logging.INFO)
  17. logger.propagate = False
  18. # 日志输出格式
  19. formatter = logging.Formatter('[%(asctime)s - ' + log_name + ':%(lineno)d] - %(levelname)s: %(message)s')
  20. if write_file:
  21. # 创建logs文件夹
  22. cur_path = os.path.dirname(os.path.realpath(__file__))
  23. log_path = os.path.join(cur_path, 'logs')
  24. # 如果不存在这个logs文件夹,就自动创建一个
  25. if not os.path.exists(log_path):
  26. os.mkdir(log_path)
  27. log_name = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d'))
  28. fh = logging.FileHandler(log_name, 'a', encoding='utf-8') # 这个是python3的
  29. # 创建一个FileHandler,用于写到本地
  30. fh.setLevel(logging.INFO)
  31. fh.setFormatter(formatter)
  32. logger.addHandler(fh)
  33. # 创建一个StreamHandler,用于输出到控制台
  34. ch = logging.StreamHandler()
  35. ch.setLevel(logging.INFO)
  36. ch.setFormatter(formatter)
  37. logger.addHandler(ch)
  38. return logger
  39. if __name__ == '__main__':
  40. print(AUTO_WRITE_LOG_FILE)
  41. pass