自学内容网 自学内容网

python——写日志到本地文件(封装成类class,调用class文件)

写日志到本地文件

1、封装成一个类class

import os
import time
import logging


class LogManager:
    def __init__(self, log_file_path, max_days=7):
        self.log_file_path = log_file_path
        self.max_days = max_days
        self.logger = self._setup_logger()

    def _setup_logger(self):
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

        file_handler = logging.FileHandler(self.log_file_path)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

        return logger

    def _delete_old_logs(self):
        if not os.path.exists(self.log_file_path):
            return
        current_time = time.time()
        day_seconds = 24 * 60 * 60
        max_seconds = self.max_days * day_seconds
        file_stat = os.stat(self.log_file_path)
        if current_time - file_stat.st_mtime > max_seconds:
            os.remove(self.log_file_path)

    def log(self, message):
        self._delete_old_logs()
        self.logger.info(message)

2、在另一个类中调用

from LogManager import LogManager
# 导入 LogManager.py 文件中的 LogManager 类

if __name__ == '__main__':
    log_manager = LogManager('test.log')
    log_manager.log('这是一条测试日志')


原文地址:https://blog.csdn.net/wy313622821/article/details/142740485

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!