log.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. def get_log(log_name="my_log", write_file=False):
  10. logging.basicConfig()
  11. logger = logging.getLogger(log_name)
  12. logger.setLevel(logging.INFO)
  13. logger.propagate = False
  14. # 日志输出格式
  15. formatter = logging.Formatter('[%(asctime)s - ' + log_name + ':%(lineno)d] - %(levelname)s: %(message)s')
  16. if write_file:
  17. # 创建logs文件夹
  18. cur_path = os.path.dirname(os.path.realpath(__file__))
  19. log_path = os.path.join(cur_path, 'logs')
  20. # 如果不存在这个logs文件夹,就自动创建一个
  21. if not os.path.exists(log_path):
  22. os.mkdir(log_path)
  23. log_name = os.path.join(log_path, '%s.log' % time.strftime('%Y_%m_%d'))
  24. fh = logging.FileHandler(log_name, 'a', encoding='utf-8') # 这个是python3的
  25. # 创建一个FileHandler,用于写到本地
  26. fh.setLevel(logging.INFO)
  27. fh.setFormatter(formatter)
  28. logger.addHandler(fh)
  29. # 创建一个StreamHandler,用于输出到控制台
  30. ch = logging.StreamHandler()
  31. ch.setLevel(logging.INFO)
  32. ch.setFormatter(formatter)
  33. logger.addHandler(ch)
  34. return logger
  35. if __name__ == '__main__':
  36. pass