logger.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. super().__init__()
  9. self.logger = logging.Logger(__name__)
  10. # self.logger = logging.getLogger(__name__)
  11. # self.logger.setLevel(clevel)
  12. if Flevel == logging.DEBUG or clevel == logging.DEBUG:
  13. formatter = logging.Formatter('[%(module)s]: (%(lineno)d) (%(asctime)s) %(message)s')
  14. else:
  15. formatter = logging.Formatter('(%(asctime)s) %(message)s')
  16. #设置CMD日志
  17. sh = logging.StreamHandler()
  18. sh.setFormatter(formatter)
  19. sh.setLevel(clevel)
  20. self.logger.addHandler(sh)
  21. #设置文件日志
  22. if path:
  23. fh = logging.FileHandler(path)
  24. fh.setFormatter(formatter)
  25. fh.setLevel(Flevel)
  26. self.logger.addHandler(fh)
  27. self.debug = self.logger.debug
  28. self.info = self.logger.info
  29. self.warning = self.logger.warning
  30. self.error = self.logger.error
  31. self.critical = self.logger.critical
  32. if __name__ == "__main__":
  33. LOG = Logger('log.txt')
  34. # LOG = Logger()
  35. LOG.debug('logger debug message')
  36. LOG.info('logger info message')
  37. LOG.warning('logger warning message')
  38. LOG.error('logger error message')
  39. LOG.critical('logger critical message')