SimpleDao
Python设置日志翻滚
2019-05-06, 访问数: 1297

可翻滚的日志: logger.py

  1. # -*- coding: utf-8 -*-
  2. import os
  3. import logging
  4. from logging.handlers import RotatingFileHandler
  5. def get_full_path(local_path):
  6. file_path = os.path.abspath(__file__)
  7. base_path = os.path.dirname(file_path)
  8. return os.path.join(base_path, local_path)
  9. LOG_LEVEL = logging.DEBUG
  10. LOG_FORMAT = '%(asctime)s %(levelname)s [%(filename)s:%(funcName)s:%(lineno)s] %(message)s'
  11. DATEFMT = '%Y-%m-%d %H:%M:%S'
  12. LOG_FILE_NAME = get_full_path('logs/app.log')
  13. LOG_FILE_MAX_SIZE = 10 * 1024 * 1024
  14. LOG_FILE_BACKUP_COUNT = 5
  15. formatter = logging.Formatter(LOG_FORMAT, datefmt=DATEFMT)
  16. console = logging.StreamHandler()
  17. console.setFormatter(formatter)
  18. rotate = RotatingFileHandler(LOG_FILE_NAME, maxBytes=LOG_FILE_MAX_SIZE, backupCount=LOG_FILE_BACKUP_COUNT)
  19. rotate.setFormatter(formatter)
  20. logger = logging.getLogger('app_common')
  21. logger.propagate = False
  22. logger.setLevel(LOG_LEVEL)
  23. logger.addHandler(console)
  24. logger.addHandler(rotate)

使用方法

  1. from logger import logger
  2. logger.info('log')