编程语言
首页 > 编程语言> > python-保存日志信息

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)

标签:logging,python,保存,mode,str,path,日志,save,logger
来源: https://www.cnblogs.com/ag-chen/p/16477289.html