Bishnu Prasad
Bishnu Prasad

Reputation: 97

Python Decorator Log file not generating

I am new to Python and learning logging technique with Decorator. For me the below code is not generating required log file. Debugged the code, getting correct message to logger statement but the file is not generating. From Test method i am call the required function where i have implemented Decorator. Please guide where i am doing mistake.

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"

My Test Method:

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

Thanks you in Advance.

Upvotes: 1

Views: 184

Answers (1)

ghchoi
ghchoi

Reputation: 5156

  1. Add finally
  2. Change filename='apiRun.log' to 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 is executed only when an exception is raised from try.

finally is always executed.

Upvotes: 2

Related Questions