2016-02-01 40 views
0

我一直在閱讀正確的日誌記錄,到目前爲止我喜歡它如何去。一切都很好,直到我試圖在主文件和我寫的一個模塊中進行日誌記錄爲止。主文件能夠寫入文件和控制檯,但導入的模塊不顯示任何內容。如果我不得不猜測,我假設我將不得不單獨配置模塊輸出,因爲我在代碼配置中使用。問題是我不知道如何或如果這是甚至是原因。我已經盡了最大努力,而不是問,但現在我在這裏。 Here是源代碼的鏈接。如果你嘗試運行它,你可能不得不改變導入,因爲當我直接導入一個文件時,pycharm不喜歡它。因此,從 「從測試導入SPEEDTEST」 到 「進口SPEEDTEST」 的文件是main.py和speedtest.py導入的模塊日誌記錄調用沒有出現

主要

import logging 
from tests import speedtest 
import time 
# Logging configuration 
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s") 
logger = logging.getLogger(__name__) 
logger.setLevel(logging.DEBUG) 

# creates a handler to deal with writing to the file 
file_handler = logging.FileHandler("log.txt", mode="w") 
file_handler.setFormatter(logFormatter) 

# handler for writing to the console 
console_handler = logging.StreamHandler() 
console_handler.setFormatter(logFormatter) 

# adds the handlers to the root logger 
logger.addHandler(file_handler) 
logger.addHandler(console_handler) 

# max speed provided 
NOMINAL_SPEED = 50 

# threshold in percentage 60% seems to be a decent amount to expect. 
THRESHOLD = 60 

# padding in percentage for severe warning 
PAD = 10 

# amount of time in between runs 
INTERVAL = 300 


class Main: 
    """ 
    Main running class 
    """ 

    def __init__(self): 
     self.speedtest = speedtest.SpeedTest(share=True) 
     self.threshold = THRESHOLD 
     self.pad = PAD 
     self.nominal = NOMINAL_SPEED 
     self.done = False 

     logger.debug("Starting main loop.") 
     while not self.done: 
      self.loop() 
      time.sleep(INTERVAL) 

    def loop(self): 
     try: 
      results = self.speedtest.run() 
     except Exception as e: 
      logger.error("Skipped running speed test this run. Will try again next time") 
      return 

     download = float(results["download"][:-7]) 
     upload = float(results["upload"][:-7]) 
     url = results["url"] 
     host = results["host"] 
     diff_download = (download/self.nominal) * 100 

     logger.debug("Current download is {} Mbps upload is {} Mbps. Share url: {} host: {}".format(download, upload, url, host)) 

     if (((self.threshold - self.pad)/100) * self.nominal) <= diff_download <= ((self.threshold/100) * self.nominal): 
      logger.info("Speed is currently at {}% nominal.".format(diff_download)) 
      self.warning() 
     elif diff_download <= ((self.threshold - self.pad)/100) * self.nominal: 
      logger.info("Speed is currently at {}% nominal. This is a problem.".format(diff_download)) 
      self.critical() 

    def warning(self): 
     pass 

    def critical(self): 
     pass 


if __name__ == "__main__": 
    Main() 

SPEEDTEST

import subprocess 
import logging 
import os 


class SpeedTest: 
    """ 
    Class to run speed test and return the results in an easy to use manner 
    """ 

    def __init__(self, share=False): 
     """ 
     Init method 
     :param share: When set to true it will also return a url to the speed test image 
     :return: 
     """ 

     self.logger = logging.getLogger(__name__) 
     self.logger.addHandler(logging.NullHandler()) 

     self._share = share 

     if share is True: 
      self.logger.debug("Share flag set to True") 
      self.cmd = ["speedtest-cli", "--share"] 
     else: 
      self.logger.debug("Share not set to true. Ignoring share url") 
      self.cmd = ["speedtest-cli"] 

    def run(self): 
     """ 
     Runs the speed test returning a dict containing upload, download, ping, and share url if wanted. 
     :return: 
     """ 

     self.logger.debug("Starting speedtest!") 

     # check_output returns the output in bytes so we use decode() to turn it into a simple string. Then we split 
     # the lines giving us a list. 
     try: 
      stdout = subprocess.check_output(self.cmd).decode().splitlines() 
     except subprocess.CalledProcessError as e: 
      self.logger.error(e) 
      raise e 
     res = {} 

     for i in stdout: 
      if "Download:" in i: 
       res["download"] = i[10:] 
      if "Upload:" in i: 
       res["upload"] = i[8:] 
      if "Hosted" in i: 
       res["host"] = i[2:] 
      if self._share is True and "Share results:" in i: 
       res["url"] = i[15:] 
      else: 
       res["url"] = None 
     return res 

    def ping(self, addr): 
     """ 
     Pings an address and returns a 1 if the connection can not be made or a 0 if it succeeds 
     :param addr: IPv4 address 
     :return: 
     """ 
     try: 
      if os.name is "nt": 
       self.logger.debug("Windows OS detected") 
       self.logger.info("Pinging {}".format(addr)) 
       subprocess.check_output(["ping", "-n", "1", addr]) 

      elif os.name is "posix": 
       self.logger.debug("Nix OS detected") 
       subprocess.check_output(["ping", "-c", "1", addr]) 
     except subprocess.CalledProcessError: 
      self.logger.warning("Returned non zero value. Is the internet working?") 
      return 1 

     return 0 

if __name__ == "__main__": 
    logging.basicConfig(level=logging.DEBUG) 

    for i in SpeedTest(share=True).run().items(): 
     print(i) 

    print(SpeedTest().ping("8.8.8.0")) 
+0

您可以將源代碼添加到SO?查看它會容易得多。 –

+0

對不起給我一點時間。目前在手機上。 –

+0

明白了。我認爲我做對了。 –

回答

0

在SPEEDTEST。 py當您致電:

logging.getLogger(__name__) 

它會創建一個記錄器對象speedtest.py,所以你將不得不單獨配置它。如果你希望它是相同的記錄器在主只需添加:

self.speedtest.logger = logger 

你主要的構造函數創建SPEEDTEST對象之後

你的另一個選擇是通過__name__作爲參數SpeedTest()並使用該參數創建記錄器(我認爲這對您來說是一個更好的選擇,因爲您在構造函數中寫入記錄器)。

+0

好吧,這是有道理的。如果我想在日誌中區分它,我需要做單獨的配置嗎? –

+0

您需要在SpeedTest()的構造函數中配置日誌。隨着你想要的格式化程度,水平等。 – eli

相關問題