日志保存到文件和控制台
log保存到文件用到 threading模块
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os.path
import time
class Log(object):
# default level
def __init__(self, write_file_format=None, log_file=None):
if write_file_format is None:
self.write_file_format = ("%(filename)s[line:%(lineno)d][%(levelname)s] - %(asctime)s: %(message)s", "%Y-%m-%d %H:%M:%S")
if log_file is None:
self.log_file = self.get_log_file()
self.console_out_log_level = logging.INFO
self.write_file_log_level = logging.INFO
self.logger = logging.getLogger(__name__)
self.logger.setLevel(level=logging.DEBUG)
@staticmethod
def get_log_file():
time_line = time.strftime('%Y%m%d', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd()) + '/'
logfile = log_path + time_line + '.log'
return logfile
def write_log(self, message):
handler = logging.FileHandler(self.log_file, mode='a')
handler.setLevel(self.write_file_log_level)
formatter = logging.Formatter(self.write_file_format[0],self.write_file_format[1])
handler.setFormatter(formatter)
# set console output format
console = logging.StreamHandler()
console.setLevel(self.console_out_log_level)
# add handler
if self.write_file_log_level == 10:
self.logger.addHandler(handler)
self.logger.addHandler(console)
# output log
self.logger.debug(message)
else:
self.logger.addHandler(handler)
self.logger.addHandler(console)
# output log
self.logger.info(message)
if __name__ == '__main__':
a = Log()
a.write_log('this is log test.')
|