python-保存日志信息
import os
import logging
class Logger:
def __init__(self, save_path: str, mode: str = 'w', logger_name: str = ''):
assert mode == 'w' or mode == 'a', "The file mode must be 'w' or 'a': {}".format(mode)
assert os.path.exists(os.path.dirname(save_path)), \
'The folder does not exist: {}'.format(os.path.dirname(save_path))
if mode == 'a':
assert os.path.exists(save_path), 'The file does not exist: {}'.format(save_path)
if logger_name == '':
formatter_str = '%(asctime)s: %(message)s'
else:
formatter_str = '%(name)s %(asctime)s %(levelname)s: %(message)s'
logging.basicConfig(
format=formatter_str,
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S',
filename=save_path,
filemode=mode
)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter(formatter_str)
console.setFormatter(formatter)
self.logger = logging.getLogger(logger_name)
self.logger.addHandler(console)
def write(self, message: str):
self.logger.info(message)
本文来自博客园,作者:漫漫长夜何时休,转载请注明原文链接:https://www.cnblogs.com/ag-chen/p/16477289.html