首页 > 解决方案 > Python 装饰器日志文件未生成

问题描述

我是 Python 新手,正在使用 Decorator 学习日志记录技术。对我来说,下面的代码没有生成所需的日志文件。调试代码,向记录器语句获取正确消息,但未生成文件。从测试方法中,我调用了我实现装饰器的所需函数。请指导我在哪里做错了。

try:
    import csv
    import requests
    import datetime
    import os
    import sys
    import logging
except Exception as e:
   print("Some Modules are missing {}".format(e))


class Meta(type):
    """ Meta class"""

    def __call__(cls, *args, **kwargs):
        instance = super(Meta, cls).__call__(*args, **kwargs)
        return instance

    def __init__(cls, name, base, attr):
        super(Meta, cls).__init__(name, base, attr)


class log(object):
    def __init__(self, func):
        self.func = func

    def __call__(self, *args, **kwargs):
        """ Wrapper Function"""

        start = datetime.datetime.now()     #start time
        Tem = self.func(*args)     #call Function
        Argument = args
        FunName = self.func.__name__        #get Function name
        end = datetime.datetime.now()       #end Time

        message =  """
                Function        : {}
                Execustion Time : {}
                Argument        : {}
                Memory          : {} Bytes
                Date            : {}                
        """.format(FunName,
                   end-start,
                   Argument,
                   sys.getsizeof(self.func),
                   start
        )

        cwd = os.getcwd();
        folder = 'Logs'
        newPath = os.path.join(cwd, folder)

        try:
            """Try to create a folder """
            os.mkdir(newPath)
        except:
            """Folder already exist """
            logging.basicConfig(filename='apiRun.log'.format(newPath), level=logging.DEBUG)
            logging.debug(message)

        return Tem


class APIHelper(metaclass=Meta):
    def __init__(self, *args, **kwargs):
        pass

    @log
    def star_wars_characters(url):
        #self.url = url
        api_response = requests.get(url)
        people = []
        if api_response.status_code == 200:
            data = api_response.json()
            for d in data['results']:
                character = []
                character.append(d['name'])
                character.append(d['height'])
                character.append(d['gender'])
                people.append(character)
            return people
        else:
            return "Bad Request"

我的测试方法:

import unittest
import csv

from com.Script.APIHelper import APIHelper

class TestAPI(unittest.TestCase):
    def _setUp(self, file_name):
        self.api = APIHelper()
        with open(file_name, "w") as self.fd:
            self.csvfile = csv.writer(self.fd, delimiter = ',')
            self.csvfile.writerow(['Name','Height','Gender'])

    def tearDown(self):
        self.fd.close()

    def test_responseNotEmpty(self):
        file_name = 'SWAPI.csv'
        self._setUp(file_name)
        people = self.api.star_wars_characters("https://swapi.dev/api/people/")
        assert type(people) is list

提前谢谢你。

标签: pythonpython-3.xpython-decorators

解决方案


  1. 添加finally
  2. 更改filename='apiRun.log'filename='{}/apiRun.log'
    try:
        """Try to create a folder """
        os.mkdir(newPath)
    except:
        """Folder already exist """
    finally:
        logging.basicConfig(filename='{}/apiRun.log'.format(newPath), level=logging.DEBUG)
        logging.debug(message)

except仅当从 引发异常时才执行try

finally总是被执行。


推荐阅读