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://blog.ytso.com/274303.html