继承logging.Logger
#!/usr/bin/env python
#-*- encoding: utf8 -*-
import sys
import logging
class MyLogger(logging.Logger):
def __init__(self,
name=None,
level=logging.DEBUG,
fmt=None,
datefmt=None,
logfile=None,
filemode='w',
stream=sys.stderr,
**kwargs):
super(MyLogger, self).__init__(name, level)
self.fmt = fmt or '[%(asctime)s %(name)s %(funcName)s %(levelname)s %(threadName)s] %(message)s'
self.datefmt = datefmt or '%Y-%m-%d %H:%M:%S'
self.formatter = logging.Formatter(self.fmt, self.datefmt)
if logfile:
self._addFilehandler(logfile, filemode)
else:
self._addStreamHandler(stream)
def _addFilehandler(self, filename, filemode):
file_hdlr = logging.FileHandler(filename, filemode)
file_hdlr.setFormatter(self.formatter)
self.addHandler(file_hdlr)
def _addStreamHandler(self, stream):
stream_hdlr = logging.StreamHandler(stream)
stream_hdlr.setFormatter(self.formatter)
self.addHandler(stream_hdlr)
if __name__ == '__main__':
logger = MyLogger()
logger.info('info message')
logger2 = MyLogger(logfile='out.log')
logger2.warn('warn message')
logger2.warn('warn message')