继承logging.Logger

    1. #!/usr/bin/env python
    2. #-*- encoding: utf8 -*-
    3. import sys
    4. import logging
    5. class MyLogger(logging.Logger):
    6. def __init__(self,
    7. name=None,
    8. level=logging.DEBUG,
    9. fmt=None,
    10. datefmt=None,
    11. logfile=None,
    12. filemode='w',
    13. stream=sys.stderr,
    14. **kwargs):
    15. super(MyLogger, self).__init__(name, level)
    16. self.fmt = fmt or '[%(asctime)s %(name)s %(funcName)s %(levelname)s %(threadName)s] %(message)s'
    17. self.datefmt = datefmt or '%Y-%m-%d %H:%M:%S'
    18. self.formatter = logging.Formatter(self.fmt, self.datefmt)
    19. if logfile:
    20. self._addFilehandler(logfile, filemode)
    21. else:
    22. self._addStreamHandler(stream)
    23. def _addFilehandler(self, filename, filemode):
    24. file_hdlr = logging.FileHandler(filename, filemode)
    25. file_hdlr.setFormatter(self.formatter)
    26. self.addHandler(file_hdlr)
    27. def _addStreamHandler(self, stream):
    28. stream_hdlr = logging.StreamHandler(stream)
    29. stream_hdlr.setFormatter(self.formatter)
    30. self.addHandler(stream_hdlr)
    31. if __name__ == '__main__':
    32. logger = MyLogger()
    33. logger.info('info message')
    34. logger2 = MyLogger(logfile='out.log')
    35. logger2.warn('warn message')
    36. logger2.warn('warn message')