把需要的所有东西都封装在一个方法中:
def init_log(save_path, mode='w'):
import logging
logger = logging.getLogger() # 不加名称设置root logger
level = logging.DEBUG
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger.setLevel(level)
# 写入文件
fh = logging.FileHandler(save_path, mode=mode)
fh.setLevel(level)
fh.setFormatter(formatter)
# 使用StreamHandler输出到屏幕
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(formatter)
# 添加两个Handler
logger.addHandler(ch)
logger.addHandler(fh)
return logger
调用时,只需要使用:
logger = init_log('test_log.log')
# 开始记录日志
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critial')
完整代码
def init_log(save_path, mode='w'):
import logging
logger = logging.getLogger() # 不加名称设置root logger
level = logging.DEBUG
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger.setLevel(level)
# 写入文件
fh = logging.FileHandler(save_path, mode=mode)
fh.setLevel(level)
fh.setFormatter(formatter)
# 使用StreamHandler输出到屏幕
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(formatter)
# 添加两个Handler
logger.addHandler(ch)
logger.addHandler(fh)
return logger
if __name__ == '__main__':
logger = init_log('test_log.log')
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critial')