LoggerConfig.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. # Author renyupeng
  2. # coding=utf-8
  3. # @Time : 2021/9/15 11:14 上午
  4. # @Site :
  5. # @File : ConfConstant.py
  6. # @Software: PyCharm
  7. # @contact: renyupeng@c-top.com.cn
  8. # @Tel 1501435553
  9. """
  10. logging配置
  11. """
  12. import logging.config
  13. import os
  14. import time
  15. from Apietl.constant.ConfConstant import ConfConstant
  16. class Loggers:
  17. def __init__(self, log_name):
  18. """初始化日志"""
  19. self.__ini_log(log_name=log_name)
  20. @staticmethod
  21. def __get_local_time():
  22. # 获取当前时间
  23. time_now = int(time.time())
  24. # 转换成localtime
  25. time_local = time.localtime(time_now)
  26. # 转换成新的时间格式(2016-05-09 18:59:20)
  27. dt = time.strftime("%Y%m%d", time_local)
  28. return dt
  29. def __ini_log(self, log_name):
  30. # 定义三种日志输出格式 开始
  31. standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
  32. '[%(levelname)s][%(message)s]' # 其中name为getlogger指定的名字
  33. simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
  34. # id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
  35. # 定义日志输出格式 结束
  36. # logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录
  37. logfile_dir = os.path.dirname(ConfConstant.LOG_DIR) # log文件的目录
  38. logfile_name = '{}_{}.log'.format(log_name, self.__get_local_time()) # log文件名
  39. # 如果不存在定义的日志目录就创建一个
  40. if not os.path.isdir(logfile_dir):
  41. os.mkdir(logfile_dir)
  42. # log文件的全路径
  43. logfile_path = os.path.join(logfile_dir, logfile_name)
  44. # log配置字典
  45. logging_dic = {
  46. 'version': 1,
  47. 'disable_existing_loggers': False,
  48. 'formatters': {
  49. 'standard': {
  50. 'format': standard_format
  51. },
  52. 'simple': {
  53. 'format': simple_format
  54. },
  55. },
  56. 'filters': {},
  57. 'handlers': {
  58. # 打印到终端的日志
  59. 'console': {
  60. 'level': 'DEBUG',
  61. 'class': 'logging.StreamHandler', # 打印到屏幕
  62. 'formatter': 'simple'
  63. },
  64. # 打印到文件的日志,收集info及以上的日志
  65. 'default': {
  66. 'level': 'DEBUG',
  67. 'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
  68. 'formatter': 'standard',
  69. 'filename': logfile_path, # 日志文件
  70. # 'maxBytes': 1024*1024*5, # 日志大小 5M
  71. 'backupCount': 5,
  72. 'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
  73. },
  74. },
  75. 'loggers': {
  76. '': {
  77. 'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
  78. 'level': ConfConstant.LOG_LEVEL,
  79. 'propagate': True, # 向上(更高level的logger)传递
  80. },
  81. },
  82. }
  83. logging.config.dictConfig(logging_dic) # 导入上面定义的logging配置
  84. logging.getLogger(__name__) # 生成一个log实例