1. 将日志信息打印到屏幕
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.info('use cpu')
logging.info('gpu num: %d', len(ctx))
2. 将日志信息打印到屏幕,并写入文档保存
class Logger(object):
level_relations = {
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'crit':logging.CRITICAL
}
def __init__(self, filename, level='info',
fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
self.logger = logging.getLogger()
self.logger.setLevel(self.level_relations.get(level))
format_str = logging.Formatter(fmt)
sh = logging.StreamHandler()
fh = logging.FileHandler(filename=filename)
self.logger.addHandler(sh)
self.logger.addHandler(fh)
timestr = datetime.datetime.now().strftime("%Y-%m-%d_%H_%M_%S")
logfilename = '%s_%s_%s_%s.log' % (args.network, args.dataset, args.loss, timestr)
dir_name = './training_log'
if not os.path.exists(dir_name):
os.mkdir(dir_name)
logfilepath = os.path.join(dir_name, logfilename)
Logger(filename=logfilepath)
logging.info('=' * 60)
logging.info('image_size %s', str(image_size))
3. 采用东八区时间
def beijing_time(sec, what):
logtime = datetime.utcnow() + timedelta(hours=8)
return logtime.timetuple()
logging.Formatter.converter = beijing_time
plain_formatter = logging.Formatter("[%(asctime)s] %(name)s %(levelname)s: %(message)s", datefmt="%m/%d %H:%M:%S")