Log.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. '''
  2. Log类
  3. '''
  4. __author__ = 'lmstack'
  5. import logging
  6. from logging import handlers
  7. import os
  8. class Mylog:
  9. def __init__(self, log_name='this_log', log_level = ''):
  10. self.logger = logging.getLogger(log_name)
  11. self._set_log_level(logging.INFO)
  12. if len(log_level) > 0:
  13. self._set_log_level(log_level)
  14. def get_logger(self):
  15. return self.logger
  16. def set_file_hl(self, file_name='all.log', log_level='info', size=1, backupCount=10):
  17. fh = handlers.RotatingFileHandler(file_name, maxBytes=size, backupCount=backupCount)
  18. fh_formatter = logging.Formatter('%(asctime)s:%(created)f:%(name)s:%(module)s:%(funcName)s:%(levelname)s:%(message)s')
  19. fh.setFormatter(fh_formatter)
  20. if len(log_level) > 0:
  21. if log_level == 'debug':
  22. fh.setLevel(logging.DEBUG)
  23. if log_level == 'info':
  24. fh.setLevel(logging.INFO)
  25. if log_level == 'warning':
  26. fh.setLevel(logging.WARNING)
  27. if log_level == 'error':
  28. fh.setLevel(logging.ERROR)
  29. self.logger.addHandler(fh)
  30. def set_stream_hl(self, log_level='info'):
  31. sh = logging.StreamHandler()
  32. sh_formatter = logging.Formatter('%(asctime)s:%(created)f:%(name)s:%(module)s:%(funcName)s:%(levelname)s:%(message)s')
  33. sh.setFormatter(sh_formatter)
  34. if len(log_level) > 0:
  35. if log_level == 'debug':
  36. sh.setLevel(logging.DEBUG)
  37. if log_level == 'info':
  38. sh.setLevel(logging.INFO)
  39. if log_level == 'warning':
  40. sh.setLevel(logging.WARNING)
  41. if log_level == 'error':
  42. sh.setLevel(logging.ERROR)
  43. self.logger.addHandler(sh)
  44. def _set_log_level(self, log_level):
  45. if log_level == 'debug':
  46. self.logger.setLevel(logging.DEBUG)
  47. if log_level == 'info':
  48. self.logger.setLevel(logging.INFO)
  49. if log_level == 'warning':
  50. self.logger.setLevel(logging.WARNING)
  51. if log_level == 'error':
  52. self.logger.setLevel(logging.ERROR)