python - 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
提前谢谢你。
解决方案
- 添加
finally
- 更改
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
总是被执行。
推荐阅读
- linux - ubuntu awk 如何获取最后一个用户和时间数据?
- sql - 搜索特定时期内唯一的文本数据会比搜索所有记录更快吗?
- javascript - 更改功能在平板电脑上不起作用,但在移动设备上可以
- php - laravel 在更新记录时对多列进行唯一验证
- java - 带有tomcat的SpringBoot应用程序在Openshift中消耗更多资源
- mongodb - ECONNREFUSED MongoDB 在 kubernetes 集群中运行
- amazon-web-services - 对 AWS 语义分割的 GPU 支持
- node.js - 在循环nodejs 10 Google Cloud Function中使全局对象可用
- ios - 在 SwiftUI 中符合 RandomAccessCollection 时,下标中的索引超出范围
- sql - mysql查询从3种类型中获取项目