import sys
from datetime import datetime
import psutil
import urllib.request
import time

class Logger(object):

    def __init__(self):
        self.number_of_request_last = 0;
        self.time = int(time.time());


    def set(self, argv):
        self.filename = argv[1];
        self.duration = int(argv[2]);
        self.delay = int(argv[3]);
        self.url = argv[4];


    def log_printer(self):
        cpu = psutil.cpu_percent(interval=0);
        req = urllib.request.urlopen("http://" + self.url + "/nginx_status");

        number_of_requests = int((str(req.read()).split())[9]);
        requests = (number_of_requests - self.number_of_request_last) / self.delay;
      
        print('{0} : {1} : {2}'.format(datetime.now().strftime('%H:%M:%S'), cpu, requests));

        self.number_of_request_last = number_of_requests;
        return str(datetime.now().strftime('%H:%M:%S')) + " " + str(cpu) + " " + str(requests);

    def start_logging(self):
        data = "";
        while int(time.time()) - self.time < self.duration:
            data += self.log_printer() + "\n";
            time.sleep(self.delay);
        f1 = open(self.filename + '.txt','w+');
        f1.write(data);
        f1.close();
        

logger = Logger();
logger.set(sys.argv);
logger.start_logging();
