日志输出及文档保存--logger

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()                           # 创建一个handler,用于输出到控制台
        fh = logging.FileHandler(filename=filename)            # 创建一个handler,用于写入日志文件
        # sh.setLevel(logging.INFO)
        # fh.setLevel(logging.INFO)
        # sh.setFormatter(format_str)                          # 设置屏幕上显示的格式
        # fh.setFormatter(format_str)                          # 设置文件里写入的格式
        self.logger.addHandler(sh)                             # 把对象加到logger里
        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)	 									   # os.makedirs()
logfilepath = os.path.join(dir_name, logfilename)
Logger(filename=logfilepath)

logging.info('=' * 60)
logging.info('image_size %s', str(image_size))

你可能感兴趣的:(开发环境)