bthtth 2021-07-16 00:00 采纳率: 50%
浏览 34

重新封装的日志在unittest中运行时报错:未关闭日志文件

1\重新封装了logging,用于记录web操作

#  web_log.py
import logging
from common import web_conf
class Log_Web_Test:

    def log_Basic(self, level="Debug", message=""):

        # 创建logger实例
        logger_test = logging.getLogger("Log_Of_Web_Test")
        logger_test.setLevel("DEBUG")

        # 创建日志输出格式
        fmt_str = '%(asctime)s-%(levelname)s-%(module)s-%(lineno)d-%(message)s'
        handler_fmt = logging.Formatter(fmt_str)

        # 获取日志输出文件的位置

        handler_test = logging.FileHandler(web_conf.path_log, "a+", "utf-8", True)    
                # 文件位置Log_Of_Web_Test.txt,确定没错,能看到其他的写入信息

        handler_test.setLevel("DEBUG")
        handler_test.setFormatter(handler_fmt)

        logger_test.addHandler(handler_test)

        if level.upper() == "DEBUG":
            logger_test.debug(message)
        if level.upper() == "INFO":
            logger_test.info(message)
        if level.upper() == "WARNING":
            logger_test.warning(message)
        if level.upper() == "ERROR":
            logger_test.error(message)
        if level.upper() == "CRITICAL":
            logger_test.critical(message)

        logger_test.removeHandler(handler_test)

    def debug(self, message):
        self.log_Basic("debug", message)

    def info(self, message):
        self.log_Basic("info", message)  # 这里提示报错  unclosed file<>

    def warning(self, message):
        self.log_Basic("warning", message)

    def error(self, message):
        self.log_Basic("error", message)

    def critical(self, message):
        self.log_Basic("critical", message)

这里测试没有问题
2\使用python + 文件名的方式运行,用例通过,不报错

img

3\使用Unittest in+文件名 ,用例通过,报错
web_log.py:40: ResourceWarning: unclosed file <_io.TextIOWrapper name='C:\Users\bth\PycharmProjects\58_web_test\output\Log_Of_Web_Test.txt' mode='a+' encoding='utf-8'>
self.log_Basic("info", message)
img

  • 写回答

1条回答 默认 最新

  • 二九筒 2022-05-17 11:35
    关注

    在后面加一个file.close()试试

    评论

报告相同问题?

问题事件

  • 创建了问题 7月16日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改