在把日志写入文件的同时在控制台输出
示例代码如下:
#coding=utf-8import loggingimport timeimport osdir = os.path.dirname(os.path.abspath('.'))log_path = dir + '\\log'class Log: def __init__(self): self.logname = os.path.join(log_path, '{0}.log'.format(time.strftime('%Y-%m-%d'))) def __printconsole(self, level, message): # 创建一个logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 创建一个handler,用于写入日志文件 fh = logging.FileHandler(self.logname,'a',encoding='utf-8') fh.setLevel(logging.DEBUG) # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 定义handler的输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) # 给logger添加handler logger.addHandler(fh) logger.addHandler(ch) # 记录一条日志 if level == 'info': logger.info(message) elif level == 'debug': logger.debug(message) elif level == 'warning': logger.warning(message) elif level == 'error': logger.error(message) logger.removeHandler(ch) logger.removeHandler(fh) # 关闭打开的文件 fh.close() def debug(self,message): self.__printconsole('debug', message) def info(self,message): self.__printconsole('info', message) def warning(self,message): self.__printconsole('warning', message) def error(self,message): self.__printconsole('error', message)if __name__ == '__main__': log = Log() log.info('info msg1000013333') log.debug('debug msg') log.warning('warning msg') log.error('error msg')
输出结果如下:
> "D:\Python27\python.exe" "D:\work\code\test\test\wirteLog.py" 2017-05-09 15:09:32,763 - root - INFO - info msg10000133332017-05-09 15:09:32,769 - root - DEBUG - debug msg2017-05-09 15:09:32,776 - root - WARNING - warning msg2017-05-09 15:09:32,782 - root - ERROR - error msg