logger.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. import logging
  3. LOGLEVEL = { 'NOTSET': logging.NOTSET, 'DEBUG' : logging.DEBUG, \
  4. 'INFO' : logging.INFO, 'WARNING' : logging.WARNING, \
  5. 'ERROR' : logging.ERROR, 'CRITICAL' : logging.CRITICAL }
  6. class Logger(object):
  7. def __init__(self, path = None, clevel = logging.INFO, Flevel = logging.INFO):
  8. self.logger = logging.Logger(__name__)
  9. # self.logger = logging.getLogger(__name__)
  10. # self.logger.setLevel(clevel)
  11. if Flevel == logging.DEBUG or clevel == logging.DEBUG:
  12. formatter = logging.Formatter('[%(module)s]: (%(lineno)d) (%(asctime)s) %(message)s')
  13. else:
  14. formatter = logging.Formatter('(%(asctime)s) %(message)s')
  15. #设置CMD日志
  16. sh = logging.StreamHandler()
  17. sh.setFormatter(formatter)
  18. sh.setLevel(clevel)
  19. self.logger.addHandler(sh)
  20. #设置文件日志
  21. if path:
  22. fh = logging.FileHandler(path)
  23. fh.setFormatter(formatter)
  24. fh.setLevel(Flevel)
  25. self.logger.addHandler(fh)
  26. self.debug = self.logger.debug
  27. self.info = self.logger.info
  28. self.warning = self.logger.warning
  29. self.error = self.logger.error
  30. self.critical = self.logger.critical
  31. if __name__ == "__main__":
  32. LOG = Logger('log.txt')
  33. # LOG = Logger()
  34. LOG.debug('logger debug message')
  35. LOG.info('logger info message')
  36. LOG.warning('logger warning message')
  37. LOG.error('logger error message')
  38. LOG.critical('logger critical message')