diff --git a/Configuration/XMLUtil.py b/Configuration/XMLUtil.py
index 41bd2ae5..08d791c8 100644
--- a/Configuration/XMLUtil.py
+++ b/Configuration/XMLUtil.py
@@ -16,8 +16,8 @@
import logging
-logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
-logger = logging.getLogger(__name__)
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
PH2ACF_VERSION = os.environ.get("PH2ACF_VERSION")
@@ -36,20 +36,20 @@ def LoadXML(filename="CMSIT.xml"):
def ShowXMLTree(XMLroot, depth=0):
depth += 1
- print("--"*(depth-1), "|", XMLroot.tag, XMLroot.attrib, XMLroot.text)
+ logger.info("--"*(depth-1), "|", XMLroot.tag, XMLroot.attrib, XMLroot.text)
for child in XMLroot:
ShowXMLTree(child,depth)
def ModifyBeboard(XMLroot, BeboardModule):
def __init__(self):
- print("Nothing Done")
+ logger.info("Nothing Done")
class HWDescription():
def __init__(self):
self.BeBoardList = []
self.Settings = {}
self.MonitoringList = []
- print("Setting HWDescription")
+ logger.info("Setting HWDescription")
def AddBeBoard(self, BeBoardModule):
self.BeBoardList.append(BeBoardModule)
@@ -278,7 +278,7 @@ def GenerateHWDescriptionXML(HWDescription,outputFile = "CMSIT_gen.xml", boardty
#Node_connection.Set('id',BeBoard.id)
#Node_connection.Set('uri',BeBoard.uri)
#Node_connection.Set('address_table',BeBoard.address_table)
- print('beboard ip is {0}'.format(BeBoard.uri))
+ logger.info('beboard ip is {0}'.format(BeBoard.uri))
Node_connection = SetNodeAttribute(Node_connection,{'id':BeBoard.id,'uri':BeBoard.uri,'address_table':BeBoard.address_table})
OpticalGroupList = BeBoard.OpticalGroupList
@@ -306,14 +306,14 @@ def GenerateHWDescriptionXML(HWDescription,outputFile = "CMSIT_gen.xml", boardty
##FIXME Add in logic to change depending on version of Ph2_ACF -> Done!
HyBridModule.SetHyBridType('RD53') #This part should stay as just RD53 (no A or B)
- print("This is the Hybrid Type: ", HyBridModule.HyBridType)
+ logger.info("This is the Hybrid Type: ", HyBridModule.HyBridType)
Node_FEPath = ET.SubElement(Node_HyBrid, HyBridModule.HyBridType+'_Files')
Node_FEPath = SetNodeAttribute(Node_FEPath,{'file':HyBridModule.File_Path})
FEList = HyBridModule.FEList
### This is where the RD53 block is being made ###
for FE in FEList:
BeBoard.boardType = boardtype
- print("This is the board type: ", BeBoard.boardType)
+ logger.info("This is the board type: ", BeBoard.boardType)
Node_FE = ET.SubElement(Node_HyBrid, BeBoard.boardType)
if 'v1' in boardtype:
Node_FE = SetNodeAttribute(Node_FE,{'Id':FE.Id, 'enable':FE.Enabled,'Lane':FE.Lane, 'eFuseCode':FE.EfuseID,'IrefCode':'-1','configFile':FE.configfile,'RxGroups':FE.RxGroups,'RxPolarity':FE.RxPolarities,'TxGroup':FE.TxGroups,'TxChannel':FE.TxChannels,'TxPolarity':FE.TxPolarities,'Comment':boardtype})
diff --git a/Configuration/dataExtraction.py b/Configuration/dataExtraction.py
index 096fa165..50268906 100644
--- a/Configuration/dataExtraction.py
+++ b/Configuration/dataExtraction.py
@@ -10,6 +10,10 @@
+
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
+
def GetTrims(password,serialNumber,debug = False):
connection = mysql.connector.connect(
host="cmsfpixdb.physics.purdue.edu",
@@ -25,21 +29,21 @@ def GetTrims(password,serialNumber,debug = False):
cursor.execute(f"select component.id from component where component.serial_number='{serialNumber}';")
results = cursor.fetchall()
if debug == True:
- print("raw ID:"+str(result))# it should look like [(778,)]
+ logger.debug("raw ID:"+str(result))# it should look like [(778,)]
parenetNum = results[0][0]
cursor.execute(f"select component.description from component where component.serial_number='{serialNumber}';")
results = cursor.fetchall() #[('TFPX CROC 1x2 HPK sensor module',)]
if debug == True:
- print("raw description"+str(results))
+ logger.debug("raw description"+str(results))
if "sensor" in str(results[0][0]):
cursor.execute(f"select component.id from component where component.parent='{parenetNum}';")
chipSensorResult=cursor.fetchall()
secondParent=chipSensorResult[0][0]
if debug == True:
- print("it is sensor module")
- print("secondParent" + str(secondParent))
+ logger.debug("it is sensor module")
+ logger.debug("secondParent" + str(secondParent))
parenetNum = secondParent
@@ -53,7 +57,7 @@ def GetTrims(password,serialNumber,debug = False):
VDDAList.append([siteNum,VDDA])
sorted_VDDAlist = sorted(VDDAList, key=lambda x: x[0])
if debug == True:
- print("sorted_VDDAlist:"+str(sorted_VDDAlist))
+ logger.debug("sorted_VDDAlist:"+str(sorted_VDDAlist))
@@ -67,7 +71,7 @@ def GetTrims(password,serialNumber,debug = False):
sorted_VDDDlist = sorted(VDDDList, key=lambda x: x[0]) #make sure the we can get VDDD value base on the order of rising chip no
if debug == True:
- print("sorted_VDDDlist:" + str(sorted_VDDDlist))
+ logger.debug("sorted_VDDDlist:" + str(sorted_VDDDlist))
connection.close()
return sorted_VDDAlist,sorted_VDDDlist
@@ -76,7 +80,7 @@ def GetTrims(password,serialNumber,debug = False):
password = getpass.getpass("Enter your password:")
serialNumber = "RH0001"
sorted_VDDAlist,sorted_VDDDlist=GetTrims(password,serialNumber)
- print("sorted_VDDAlist(in order site,trim value):" + str(sorted_VDDAlist))
- print("VDDD:" + str(sorted_VDDDlist))
+ logger.info("sorted_VDDAlist(in order site,trim value):" + str(sorted_VDDAlist))
+ logger.info("VDDD:" + str(sorted_VDDDlist))
diff --git a/F4T_Monitoring/F4TMonitor.py b/F4T_Monitoring/F4TMonitor.py
index 5a951c75..d72c3e33 100644
--- a/F4T_Monitoring/F4TMonitor.py
+++ b/F4T_Monitoring/F4TMonitor.py
@@ -7,6 +7,9 @@
import matplotlib, threading, time, csv, yagmail, os
from datetime import datetime
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
+
class F4TMonitor():
def __init__(self):
self.alertRecipients=[] #emails
@@ -90,7 +93,7 @@ def updateData(self):
try:
data, _ = self.sock.recvfrom(2048)
data = data.decode('utf-8')
- print(data)
+ logger.info(data)
if data[0]=="!":
self.logFile="dht_logs_"+datetime.now().strftime("%Y-%m-%d %H:%M:%S")+".csv"
@@ -122,7 +125,7 @@ def updateData(self):
string = "Arduino connection timed out."
else:
string = str(e)
- print(e)
+ logger.error(e)
self.tailData.insert(0,string)
if len(self.tailData)>6: self.tailData.pop()
diff --git a/Gui/GUIutils/DBConnection.py b/Gui/GUIutils/DBConnection.py
index c0202015..706a107c 100644
--- a/Gui/GUIutils/DBConnection.py
+++ b/Gui/GUIutils/DBConnection.py
@@ -14,6 +14,8 @@
import traceback
from PyQt5.QtWidgets import QMessageBox
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
# from Gui.GUIutils.settings import *
from Gui.GUIutils.guiUtils import (
@@ -50,8 +52,8 @@ def QtStartConnection(TryUsername, TryPassword, TryHostAddress, TryDatabase):
connection_timeout=5000,
)
except (ValueError, RuntimeError, TypeError, NameError, mysql.connector.Error) as err:
- print("Error establishing connection:", err)
- print(traceback.format_exc())
+ logger.error("Error establishing connection:", err)
+ logger.error(traceback.format_exc())
msg = QMessageBox()
msg.information(
None,
@@ -178,12 +180,12 @@ def getLocalTests(module_id, columns=[]):
test = formatter(dirName, columns, part_id=str(module_id))
localTests.append(test)
except Exception as err:
- print(
+ logger.error(
"Error detected while formatting the directory name, {}".format(
repr(err)
)
)
- print(traceback.format_exc())
+ logger.error(traceback.format_exc())
else:
for dirName in dirList:
# getFiles = subprocess.run('find {0} -mindepth 1 -maxdepth 1 -type f -name "*.root" '.format(dirName), shell=True, stdout=subprocess.PIPE)
@@ -201,12 +203,12 @@ def getLocalTests(module_id, columns=[]):
)
localTests.append(test)
except Exception as err:
- print(
+ logger.error(
"Error detected while formatting the directory name, {}".format(
repr(err)
)
)
- print(traceback.format_exc())
+ logger.error(traceback.format_exc())
return localTests
@@ -310,8 +312,8 @@ def describeTable(dbconnection, table, KeepAutoIncre=False):
header = list(map(lambda x: alltuple[x][0], range(0, len(alltuple))))
return list(compress(header, auto_incre_filter))
except mysql.connector.Error as error:
- print("Failed describing MySQL table:", error)
- print(traceback.format_exc())
+ logger.error("Failed describing MySQL table:", error)
+ logger.error(traceback.format_exc())
return []
@@ -345,8 +347,8 @@ def retrieveWithConstraint(dbconnection, table, *args, **kwargs):
allList = [list(i) for i in alltuple]
return allList
except mysql.connector.Error as error:
- print("Failed retrieving MySQL table:", error)
- print(traceback.format_exc())
+ logger.error("Failed retrieving MySQL table:", error)
+ logger.error(traceback.format_exc())
return []
@@ -374,8 +376,8 @@ def retrieveWithConstraintSyntax(dbconnection, table, syntax, **kwargs):
allList = [list(i) for i in alltuple]
return allList
except mysql.connector.Error as error:
- print("Failed retrieving MySQL table:{}".format(error))
- print(traceback.format_exc())
+ logger.error("Failed retrieving MySQL table:{}".format(error))
+ logger.error(traceback.format_exc())
return []
@@ -400,8 +402,8 @@ def retrieveGenericTable(dbconnection, table, **kwargs):
allList = [list(i) for i in alltuple]
return allList
except Exception as error:
- print("Failed retrieving MySQL table:{}".format(error))
- print(traceback.format_exc())
+ logger.error("Failed retrieving MySQL table:{}".format(error))
+ logger.error(traceback.format_exc())
return []
@@ -425,8 +427,8 @@ def insertGenericTable(dbconnection, table, args, data):
dbconnection.commit()
return True
except Exception as error:
- print("Failed inserting MySQL table {}: {}".format(table, error))
- print(traceback.format_exc())
+ logger.error("Failed inserting MySQL table {}: {}".format(table, error))
+ logger.error(traceback.format_exc())
return False
@@ -446,8 +448,8 @@ def createNewUser(dbconnection, args, data):
dbconnection.commit()
return True
except Exception as err:
- print("Failed to create new user:", err)
- print(traceback.format_exc())
+ logger.error("Failed to create new user:", err)
+ logger.error(traceback.format_exc())
return False
@@ -492,8 +494,8 @@ def updateGenericTable(dbconnection, table, column, data, **kwargs):
dbconnection.commit()
return True
except mysql.connector.Error as error:
- print("Failed updating MySQL table {}: {}".format(table, error))
- print(traceback.format_exc())
+ logger.error("Failed updating MySQL table {}: {}".format(table, error))
+ logger.error(traceback.format_exc())
return False
@@ -506,7 +508,7 @@ def getByColumnName(column_name, header, databody):
try:
index = header.index(column_name)
except ValueError:
- print("column_name not found")
+ logger.error("column_name not found")
output = list(map(lambda x: databody[x][index], range(0, len(databody))))
return output
@@ -529,7 +531,7 @@ def get_connection(self):
def GetTrim(self, serialNumber, debug=False):
connection = self.connection
if connection == "Offline" or connection == []:
- print("DB is offline")
+ logger.error("DB is offline")
return [], []
connection.connect()
cursor = connection.cursor()
@@ -547,7 +549,7 @@ def GetTrim(self, serialNumber, debug=False):
)
results = cursor.fetchall() # [('TFPX CROC 1x2 HPK sensor module',)]
if debug:
- print("raw description" + str(results))
+ logger.debug("raw description" + str(results))
if "sensor" in str(results[0][0]):
cursor.execute(
@@ -556,8 +558,8 @@ def GetTrim(self, serialNumber, debug=False):
chipSensorResult = cursor.fetchall()
secondParent = chipSensorResult[0][0]
if debug:
- print("it is sensor module")
- print("secondParent" + str(secondParent))
+ logger.debug("it is sensor module")
+ logger.debug("secondParent" + str(secondParent))
parenetNum = secondParent
# get VDDA value
@@ -572,7 +574,7 @@ def GetTrim(self, serialNumber, debug=False):
VDDAList.append([siteNum, VDDA])
sorted_VDDAlist = sorted(VDDAList, key=lambda x: x[0])
if debug:
- print("sorted_VDDAlist:" + str(sorted_VDDAlist))
+ logger.debug("sorted_VDDAlist:" + str(sorted_VDDAlist))
VDDDList = []
cursor.execute(
@@ -588,7 +590,7 @@ def GetTrim(self, serialNumber, debug=False):
VDDDList, key=lambda x: x[0]
) # make sure the we can get VDDD value base on the order of rising chip no
if debug:
- print("sorted_VDDDlist:" + str(sorted_VDDDlist))
+ logger.debug("sorted_VDDDlist:" + str(sorted_VDDDlist))
connection.close()
return sorted_VDDAlist, sorted_VDDDlist
diff --git a/Gui/GUIutils/guiUtils.py b/Gui/GUIutils/guiUtils.py
index 4a5ed3c8..1c9d6454 100644
--- a/Gui/GUIutils/guiUtils.py
+++ b/Gui/GUIutils/guiUtils.py
@@ -86,8 +86,8 @@ def ConfigureTest(Test, Module_ID, Output_Dir, Input_Dir):
try:
os.makedirs(test_dir)
except OSError:
- print("Can not create directory: {0}".format(test_dir))
- print(traceback.format_exc())
+ logger.error("Can not create directory: {0}".format(test_dir))
+ logger.error(traceback.format_exc())
time = datetime.utcnow()
timeRound = time - timedelta(microseconds=time.microsecond)
time_stamp = timeRound.isoformat() + "_UTC"
@@ -104,8 +104,8 @@ def ConfigureTest(Test, Module_ID, Output_Dir, Input_Dir):
try:
os.makedirs(Output_Dir)
except OSError as e:
- print(f"OutputDir not created: {e}")
- print(traceback.format_exc())
+ logger.error(f"OutputDir not created: {e}")
+ logger.error(traceback.format_exc())
return "", ""
# FIXME:
@@ -135,8 +135,8 @@ def isActive(dbconnection):
else:
return False
except Exception as err:
- print("Unexpected form, {}".format(repr(err)))
- print(traceback.format_exc())
+ logger.error("Unexpected form, {}".format(repr(err)))
+ logger.error(traceback.format_exc())
return False
@@ -222,7 +222,7 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
# print('lenth of XML dict is {0}'.format(len(updatedXMLValues)))
if len(updatedXMLValues) > 0:
changeMade = True
- print(updatedXMLValues)
+ logger.error(updatedXMLValues)
for Node in root.findall(".//Settings"):
# print("Found Settings Node!")
@@ -233,14 +233,14 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
chipKeyName = "{0}/{1}".format(
HyBridNode.attrib["Id"], RD53Node.attrib["Id"]
)
- print("chipKeyName is {0}".format(chipKeyName))
+ logger.error("chipKeyName is {0}".format(chipKeyName))
if len(updatedXMLValues[chipKeyName]) > 0:
for key in updatedXMLValues[chipKeyName].keys():
Node.set(key, str(updatedXMLValues[chipKeyName][key]))
except Exception as error:
- print("Failed to set up the XML file, {}".format(error))
- print(traceback.format_exc())
+ logger.error("Failed to set up the XML file, {}".format(error))
+ logger.error(traceback.format_exc())
try:
logger.info(updatedGlobalValue)
@@ -251,18 +251,18 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
if len(updatedGlobalValue[1]) > 0:
if Node.attrib["name"] == "TargetThr":
Node.text = updatedGlobalValue[1]["TargetThr"]
- print(
+ logger.info(
"TargetThr value has been set to {0}".format(
updatedGlobalValue[1]["TargetThr"]
)
)
except Exception:
- print(
+ logger.error(
"Failed to update the TargetThr value, {0}".format(
updatedGlobalValue[1]["TargetThr"]
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
try:
if changeMade:
@@ -278,8 +278,8 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
os.path.join(Output_Dir, f"CMSIT_{BeBoardName}.xml"))
except OSError:
- print("Can not copy the XML files {0} to {1}".format(InputFile, Output_Dir))
- print(traceback.format_exc())
+ logger.error("Can not copy the XML files {0} to {1}".format(InputFile, Output_Dir))
+ logger.error(traceback.format_exc())
try:
shutil.copyfile("{0}/CMSIT_{1}.xml".format(Output_Dir, BeBoardName),
"{0}/test/CMSIT_{1}.xml".format(os.environ.get("PH2ACF_BASE_DIR"), BeBoardName)
@@ -291,7 +291,7 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
Output_Dir, BeBoardName, os.environ.get("PH2ACF_BASE_DIR")
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
##########################################################################
@@ -301,7 +301,7 @@ def SetupXMLConfigfromFile(InputFile, Output_Dir, BeBoardName=""):
def SetupRD53Config(Input_Dir, Output_Dir, RD53Dict):
for key in RD53Dict.keys():
try:
- print("Doing the copy thing in guiUtils")
+ logger.info("Doing the copy thing in guiUtils")
shutil.copyfile(
"{0}/CMSIT_RD53_{1}_OUT.txt".format(Input_Dir, key),
"{0}/CMSIT_RD53_{1}_IN.txt".format(Output_Dir, key)
@@ -312,7 +312,7 @@ def SetupRD53Config(Input_Dir, Output_Dir, RD53Dict):
Output_Dir, key
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
try:
shutil.copyfile(
"{0}/CMSIT_RD53_{1}_IN.txt".format(Output_Dir, key),
@@ -325,7 +325,7 @@ def SetupRD53Config(Input_Dir, Output_Dir, RD53Dict):
Output_Dir, key, os.environ.get("PH2ACF_BASE_DIR")
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
##########################################################################
@@ -345,7 +345,7 @@ def SetupRD53ConfigfromFile(InputFileDict, Output_Dir):
InputFileDict[key], Output_Dir
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
try:
shutil.copyfile(
os.path.join(Output_Dir, f"CMSIT_RD53_{key}_IN.txt"),
@@ -357,7 +357,7 @@ def SetupRD53ConfigfromFile(InputFileDict, Output_Dir):
Output_Dir, key, os.environ.get("PH2ACF_BASE_DIR")
)
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
##########################################################################
@@ -377,7 +377,7 @@ def CheckXMLValue(pFilename, pAttribute):
for Node in root.findall(".//Setting"):
if Node.attrib["name"] == pAttribute:
# The next line should be done using logger, not print.
- print("{0} is set to {1}.".format(pAttribute, Node.text))
+ logger.info("{0} is set to {1}.".format(pAttribute, Node.text))
##########################################################################
@@ -409,9 +409,9 @@ def GenerateXMLConfig(BeBoard, testName, outputDir, txt_files:dict, **arg):
moduleType = module.getModuleType()
hdiVersion = module.getHDIVersion()
registerKey = "{0}_HDIv{1}".format(moduleType.replace(" ", "_"), hdiVersion)
- print('register key is {0}'.format(registerKey))
+ logger.info('register key is {0}'.format(registerKey))
RegisterSettingsList = RegisterSettings_dict[registerKey]
- print("I see that the hdi version is {0}".format(hdiVersion))
+ logger.info("I see that the hdi version is {0}".format(hdiVersion))
RxPolarities = (
"1"
@@ -447,7 +447,7 @@ def GenerateXMLConfig(BeBoard, testName, outputDir, txt_files:dict, **arg):
# Sets up all the chips on the module and adds them to the hybrid module to then be stored in the class
for chip in module.getChips().values():
- print("chip {0} status is {1}".format(chip.getID(), chip.getStatus()))
+ logger.info("chip {0} status is {1}".format(chip.getID(), chip.getStatus()))
FEChip = FE()
if (module.getModuleName(), module.getFMCPort(), chip.getID()) in txt_files.keys():
txt_file = txt_files[module.getModuleName(), module.getFMCPort(), chip.getID()]
@@ -661,7 +661,7 @@ def formatter(DirName, columns, **kwargs):
else:
ReturnList[indexGrade] = -1
except Exception:
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
else:
pass
diff --git a/Gui/QtGUIutils/LaudaApp.py b/Gui/QtGUIutils/LaudaApp.py
index 509a9bc9..65a7d513 100644
--- a/Gui/QtGUIutils/LaudaApp.py
+++ b/Gui/QtGUIutils/LaudaApp.py
@@ -84,7 +84,7 @@ def setTemperature(self):
try:
self.myLauda.set("TEMPERATURE_TARGET", float(self.setTempEdit.text()))
except ValueError:
- print("Temperature target must be a float.")
+ logger.error("Temperature target must be a float.")
logger.error(traceback.format_exc())
diff --git a/Gui/QtGUIutils/PeltierCoolingApp.py b/Gui/QtGUIutils/PeltierCoolingApp.py
index 724fa4fd..cff777e0 100644
--- a/Gui/QtGUIutils/PeltierCoolingApp.py
+++ b/Gui/QtGUIutils/PeltierCoolingApp.py
@@ -178,7 +178,7 @@ def setPowerStatus(self, power):
self.powerStatus.setPixmap(self.redledpixmap)
self.powerStatusValue = 0
else:
- print("Unkown power status")
+ logger.error("Unkown power status")
def powerToggle(self):
if self.powerStatusValue == 0:
@@ -210,7 +210,7 @@ def setPolarityStatus(self, polarity):
self.polarityValue = "HEAT WP2+ and WP1-"
self.polarityButton.setText(self.polarityValue)
else:
- print("Unexpected value sent back from polarity change function")
+ logger.error("Unexpected value sent back from polarity change function")
def polarityToggle(self):
if self.polarityValue == "HEAT WP1+ and WP2-":
@@ -220,7 +220,7 @@ def polarityToggle(self):
polarityCommand = "0"
self.polarityValue = "HEAT WP1+ and WP2-"
else:
- print("Unexpected value read for polarity")
+ logger.error("Unexpected value read for polarity")
return
self.pelt.sendCommand(
self.pelt.createCommand(
@@ -327,7 +327,7 @@ def controllerMonitoring2(self):
def tempLimit(self, temp):
if temp >= 35:
self.closeEvent() # Will change this to take effect if the code runs
- print("Temperature too high")
+ logger.error("Temperature too high")
return
diff --git a/Gui/QtGUIutils/QtApplication.py b/Gui/QtGUIutils/QtApplication.py
index aed5c7de..5a9a1bd2 100644
--- a/Gui/QtGUIutils/QtApplication.py
+++ b/Gui/QtGUIutils/QtApplication.py
@@ -209,7 +209,7 @@ def setLoginUI(self):
QApplication.setStyle(QStyleFactory.create("Fusion"))
QApplication.setPalette(darkPalette)
else:
- print("This GUI supports Win/Linux/MacOS only")
+ logger.error("This GUI supports Win/Linux/MacOS only")
self.show()
def initLog(self):
@@ -354,7 +354,7 @@ def destroyLogin(self):
def checkLogin(self):
expert_string = "_*"
if self.UsernameEdit.text() not in ["local", "localexpert"]:
- print("Connecting to Panthera...")
+ logger.info("Connecting to Panthera...")
credentials = {
"username": self.UsernameEdit.text()[0 : -(len(expert_string))]
if self.UsernameEdit.text().endswith(expert_string)
@@ -489,7 +489,7 @@ def createMain(self):
)
self.FwDict[firmwareName] = BeBoard
except Exception as err:
- print("Failed to list the firmware: {}".format(repr(err)))
+ logger.error("Failed to list the firmware: {}".format(repr(err)))
logger.error(traceback.format_exc())
logger.debug(f"Setup FC7s with the following FC7:\n{self.FwDict}")
@@ -1001,7 +1001,7 @@ def connect_devices(self):
if coldbox:
temperature = coldbox.read_channel("TEMPERATURE_MEASURED", channel=0)
for number in self.instruments.get_modules().keys():
- print("temperature", temperature) # self.instruments.get_temperature()[number]["cb"]
+ logger.info("temperature", temperature) # self.instruments.get_temperature()[number]["cb"]
if lv_on or hv_on:
self.instruments.off()
if self.expertMode:
@@ -1057,7 +1057,7 @@ def reconnectDevices(self):
logger.info("You are running in manual mode. Reconnectingdoes nothing")
def reCreateMain(self):
- print("Refreshing the main page")
+ logger.info("Refreshing the main page")
self.createMain()
self.checkFirmware()
@@ -1136,7 +1136,7 @@ def runThermalTest(self):
)
return
# Import icicle module for temperature chamber
- print(site_settings.temp_chamber_resource)
+ logger.info(site_settings.temp_chamber_resource)
#temp_chamber = F4TTempChamber(resource=site_settings.temp_chamber_resource)
#with temp_chamber:
@@ -1165,7 +1165,7 @@ def openNewTest(self):
for firmware, board_object in self.FwDict.items()
if firmware in self.ActiveFC7s.values()
]
- print(f"FwModule is: {[board.getBoardName() for board in FwModule]}")
+ logger.info(f"FwModule is: {[board.getBoardName() for board in FwModule]}")
self.StartNewTest = QtStartWindow(self, FwModule)
self.NewTestButton.setDisabled(True)
@@ -1317,7 +1317,7 @@ def goExpert(self):
###############################################################
@QtCore.pyqtSlot()
def GlobalStop(self):
- print("Critical status detected: Emitting Global Stop signal")
+ logger.error("Critical status detected: Emitting Global Stop signal")
self.globalStop.emit()
self.instruments.off()
if self.expertMode:
@@ -1358,7 +1358,7 @@ def closeEvent(self, event):
self.tessie_widget.stop_temperature_monitoring()
except Exception:
logger.debug("Failed to stop Tessie monitoring cleanly during application shutdown")
- print("Application terminated")
+ logger.error("Application terminated")
if self.instruments is not None:
self.instruments.off()
diff --git a/Gui/QtGUIutils/QtDBConsoleWindow.py b/Gui/QtGUIutils/QtDBConsoleWindow.py
index 75342900..3dcc60c6 100644
--- a/Gui/QtGUIutils/QtDBConsoleWindow.py
+++ b/Gui/QtGUIutils/QtDBConsoleWindow.py
@@ -37,7 +37,9 @@
from Gui.QtGUIutils.QtViewTableTab import QtViewTableTab
from Gui.QtGUIutils.QtImageInsertionTab import QtImageInsertionTab
from Gui.QtGUIutils.QtImageViewerTab import QtImageViewerTab
-from Gui.python.logging_config import logger
+from Gui.python.logging_config import get_logger
+
+logger = get_logger(__name__)
import traceback
@@ -510,7 +512,7 @@ def fillRPRequest(self):
time_string = getByColumnName("date_sent", header, shipmentInfo)[
0
].strftime("%m/%d/%Y, %H:%M:%S")
- print(time_string)
+ logger.info(time_string)
self.RPDateSentEdit.setDateTime(QDateTime.fromString(time_string))
self.RPCarrierEdit.setText(
getByColumnName("carrier", header, shipmentInfo)[0]
@@ -1204,7 +1206,7 @@ def closeEvent(self, event):
)
if reply == QMessageBox.Yes:
- print("DB console terminated")
+ logger.info("DB console terminated")
self.release()
event.accept()
else:
diff --git a/Gui/QtGUIutils/QtModuleReviewWindow.py b/Gui/QtGUIutils/QtModuleReviewWindow.py
index 74b287cf..8270c5f8 100644
--- a/Gui/QtGUIutils/QtModuleReviewWindow.py
+++ b/Gui/QtGUIutils/QtModuleReviewWindow.py
@@ -59,7 +59,7 @@ def __init__(self, master, info=None):
"root_file",
]
# Fixme: QTimer to be added to update the page automatically
- print("The review window got opened")
+ logger.debug("The review window got opened")
self.mainLayout = QGridLayout()
self.setLayout(self.mainLayout)
@@ -223,26 +223,26 @@ def connectDB(self):
return
def openDQM(self, DQMFile):
- print("Open" + DQMFile)
+ logger.debug("Open" + DQMFile)
GetTBrowser(DQMFile)
- print("Close" + DQMFile)
+ logger.debug("Close" + DQMFile)
def syncDB(self):
- print("syncDB button was pushed!")
+ logger.debug("syncDB button was pushed!")
if not isActive(self.connection):
return
- print("syncDB is trying to do a thing")
+ logger.debug("syncDB is trying to do a thing")
selectedrows = self.view.selectionModel().selectedRows()
- print("the selected rows are {0}".format(selectedrows))
+ logger.debug("the selected rows are {0}".format(selectedrows))
for index in selectedrows:
try:
rowNumber = index.row()
if self.proxy.data(self.proxy.index(rowNumber, 1)) != "Local":
- print("This record is verified to be Non-local")
+ logger.debug("This record is verified to be Non-local")
continue
if self.proxy.data(self.proxy.index(rowNumber, 1)) == "Local":
- print("trying to send local stuff to DB")
+ logger.debug("trying to send local stuff to DB")
################################
## Block to get binary Info
################################
@@ -250,9 +250,9 @@ def syncDB(self):
localDir = self.proxy.data(
self.proxy.index(rowNumber, 8)
) # This is a temporary hack!!!
- print("local dir is {0}".format(localDir))
+ logger.debug("local dir is {0}".format(localDir))
if localDir != "":
- print("Local Directory found in : {}".format(localDir))
+ logger.debug("Local Directory found in : {}".format(localDir))
getFiles = subprocess.run(
'find {0} -mindepth 1 -maxdepth 1 -type f -name "*.root" '.format(
@@ -262,7 +262,7 @@ def syncDB(self):
stdout=subprocess.PIPE,
)
fileList = getFiles.stdout.decode("utf-8").rstrip("\n").split("\n")
- print("the filelist is {0}".format(fileList))
+ logger.debug("the filelist is {0}".format(fileList))
if fileList == [""]:
logger.warning(
"No ROOT file found in the local folder, skipping the record..."
@@ -273,7 +273,7 @@ def syncDB(self):
self.proxy.index(rowNumber, self.columns.index("part_id") + 2)
)
for submitFile in fileList:
- print("Submitting {}".format(submitFile))
+ logger.debug("Submitting {}".format(submitFile))
data_id = hashlib.md5(
"{}".format(submitFile).encode()
).hexdigest()
@@ -317,7 +317,7 @@ def syncDB(self):
configcolumns = []
configdata = []
for configInFile in configInFileList:
- print("config files are: {0}".format(configInFile))
+ logger.debug("config files are: {0}".format(configInFile))
if configInFile != [""]:
configcolumns.append(
"Chip{}InConfig".format(configInFile.split("_")[-2])
@@ -338,7 +338,7 @@ def syncDB(self):
xmlcolumns = []
xmldata = []
if len(XMLFileList) > 1:
- print("Warning! There are multiple xml files here!")
+ logger.warning("Warning! There are multiple xml files here!")
for XMLFile in XMLFileList:
if XMLFile != [""]:
xmlcolumns.append("xml_file")
@@ -391,7 +391,7 @@ def syncDB(self):
insertGenericTable(
self.connection, "module_tests", SubmitArgs, Value
)
- print("trying to insert table")
+ logger.debug("trying to insert table")
except Exception:
logger.error(traceback.format_exc())
except Exception:
diff --git a/Gui/QtGUIutils/QtRunWindow.py b/Gui/QtGUIutils/QtRunWindow.py
index 1120376e..4665d5af 100644
--- a/Gui/QtGUIutils/QtRunWindow.py
+++ b/Gui/QtGUIutils/QtRunWindow.py
@@ -492,7 +492,7 @@ def refreshHistory(self):
# self.view.setModel(self.proxy)
# self.view.setEditTriggers(QAbstractItemView.NoEditTriggers)
# self.view.update()
- print("attempting to update status in history")
+ logger.debug("attempting to update status in history")
self.HistoryLayout.removeWidget(self.StatusTable)
self.StatusTable.setRowCount(0)
for test, test_results in zip(self.finished_tests, self.modulestatus):
@@ -546,7 +546,7 @@ def sendProceedSignal(self):
# self.runNext.set()
def customizeTest(self):
- print("Customize configuration")
+ logger.debug("Customize configuration")
self.CustomizedButton.setDisabled(True)
self.RunButton.setDisabled(True)
self.CustomizedWindow = QtCustomizeWindow(self, self.testHandler.rd53_file)
@@ -729,7 +729,7 @@ def closeEvent(self, event):
if reply == QMessageBox.Yes:
self.release()
- print(f"self.master.instruments: {self.master.instruments}")
+ logger.info(f"self.master.instruments: {self.master.instruments}")
if self.master.instruments:
self.onPowerSignal()
diff --git a/Gui/QtGUIutils/QtStartWindow.py b/Gui/QtGUIutils/QtStartWindow.py
index d8716526..8a8d233d 100644
--- a/Gui/QtGUIutils/QtStartWindow.py
+++ b/Gui/QtGUIutils/QtStartWindow.py
@@ -100,18 +100,18 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
boardtype = "RD53B"
else:
boardtype = "RD53A"
- print("board type is: {0}".format(boardtype))
+ logger.info("board type is: {0}".format(boardtype))
# updating uri value in template xml file with correct fc7 ip address, as specified in siteSettings.py
# fc7_ip = site_settings.FC7List[pfirmwareName] #Commented because I don't think we need it. Remove line after test.
- print("The fc7 ip is: {0}".format(fc7_ip))
+ logger.info("The fc7 ip is: {0}".format(fc7_ip))
uricmd = "sed -i -e 's/fc7-1/{0}/g' {1}/Gui/CMSIT_{2}.xml".format(
fc7_ip, os.environ.get("GUI_dir"), boardtype
)
subprocess.call([uricmd], shell=True)
- print("updated the uri value")
+ logger.debug("updated the uri value")
firmwareImage = firmware_image[module_type]
- print("checking if firmware is on the SD card for {}".format(firmwareImage))
+ logger.info("checking if firmware is on the SD card for {}".format(firmwareImage))
fwlist = subprocess.run(
[
"fpgaconfig",
@@ -124,14 +124,14 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
)
# fwlist = subprocess.run(["fpgaconfig","-c",os.environ.get('PH2ACF_BASE_DIR')+'/test/CMSIT_{}.xml'.format(boardtype),"-l"],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
- print("firmwarelist is {0}".format(fwlist.stdout.decode("UTF-8")))
- print("firmwareImage is {0}".format(firmwareImage))
+ logger.info("firmwarelist is {0}".format(fwlist.stdout.decode("UTF-8")))
+ logger.info("firmwareImage is {0}".format(firmwareImage))
if firmwareImage in fwlist.stdout.decode("UTF-8"):
FWisPresent = True
- print("firmware found")
+ logger.info("firmware found")
else:
try:
- print(
+ logger.info(
"Saving fw image {0} to SD card".format(
os.environ.get("GUI_dir")
+ "/FirmwareImages/"
@@ -157,7 +157,7 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
stderr=subprocess.PIPE,
)
# self.fw_process.start("fpgaconfig",["-c","CMSIT.xml","-f","{}".format(os.environ.get("GUI_dir")+'/FirmwareImages/' + self.firmwareImage),"-i","{}".format(self.firmwareImage)])
- print(fwsave.stdout.decode("UTF-8"))
+ logger.info(fwsave.stdout.decode("UTF-8"))
FWisPresent = True
except OSError:
logger.error(
@@ -170,7 +170,7 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
logger.error(traceback.format_exc())
if FWisPresent:
- print("Loading FW image")
+ logger.info("Loading FW image")
fwload = subprocess.run(
[
"fpgaconfig",
@@ -183,9 +183,9 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
- print(fwload.stdout.decode("UTF-8"))
- print("resetting beboard")
- print(
+ logger.info(fwload.stdout.decode("UTF-8"))
+ logger.debug("resetting beboard")
+ logger.info(
f"command: CMSITminiDAQ -f {os.environ.get('GUI_dir') + '/Gui/CMSIT_{}.xml'.format(boardtype)} -r"
)
fwreset = subprocess.run(
@@ -199,10 +199,10 @@ def checkFwPar(pfirmwareName, module_type, fc7_ip):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
- print(fwreset.stdout.decode("UTF-8"))
- print(fwreset.stderr.decode("UTF-8"))
+ logger.info(fwreset.stdout.decode("UTF-8"))
+ logger.info(fwreset.stderr.decode("UTF-8"))
- print("Firmware image is now loaded")
+ logger.debug("Firmware image is now loaded")
logger.debug("Made it to turn on LV")
return True
except Exception:
@@ -674,7 +674,7 @@ def openRunWindow(self):
return
for beboard in self.firmwareDescription:
- print(beboard)
+ logger.info(beboard)
self.info = self.TestCombo.currentText()
@@ -746,14 +746,14 @@ def closeEvent(self, event):
if self.master.instruments:
self.master.instruments.off(hv_delay=0.5, hv_step_size=10)
- print("Window closed")
+ logger.debug("Window closed")
else:
logger.info(
" You are running in manual mode."
" You must turn off powers supplies yourself."
)
except Exception:
- print(
+ logger.error(
"Waring: Incident detected while trying to turn of power supply, please check power status"
)
logger.error(traceback.format_exc())
diff --git a/Gui/python/ANSIColoringParser.py b/Gui/python/ANSIColoringParser.py
index 73014d20..79020b16 100644
--- a/Gui/python/ANSIColoringParser.py
+++ b/Gui/python/ANSIColoringParser.py
@@ -1,3 +1,6 @@
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
+
ConvertForSpan = {
b"<": b"<",
b">": b">",
@@ -64,4 +67,4 @@ def parseANSI(text):
for line in multilines.split("\n"):
num, text = parseANSI(line)
- print(text)
+ logger.info(text)
diff --git a/Gui/python/ArduinoWidget.py b/Gui/python/ArduinoWidget.py
index 10282a97..5c1018de 100755
--- a/Gui/python/ArduinoWidget.py
+++ b/Gui/python/ArduinoWidget.py
@@ -79,7 +79,7 @@ def listResources(self):
self.ResourcesManager = visa.ResourceManager("@py")
try:
self.ResourcesList = self.ResourcesManager.list_resources()
- print(self.ResourcesList)
+ logger.info(self.ResourcesList)
self.getDeviceName()
return list(self.deviceMap.keys())
except Exception as err:
@@ -250,7 +250,7 @@ def setSerial(self, deviceName, baudRate):
deviceName, baudRate=baudMap[baudRate], readyRead=self.receive
)
self.serial.open(QIODevice.ReadOnly)
- print(f"Serial status: {self.serial.isOpen()}")
+ logger.info(f"Serial status: {self.serial.isOpen()}")
if not self.serial.isOpen():
self.ArduinoMeasureValue.setStyleSheet("QLabel {color : red}")
diff --git a/Gui/python/CustomizedWidget.py b/Gui/python/CustomizedWidget.py
index 601fc79a..e266d479 100644
--- a/Gui/python/CustomizedWidget.py
+++ b/Gui/python/CustomizedWidget.py
@@ -213,7 +213,7 @@ def __init__(self, master, pChipType, serialNumber="RH0009"):
# f"Module {serialNumber} chip layout does not correspond to typical {pChipType} chip layouts. Please modify the trim values manually.",
# QMessageBox.Ok
# )
- print(
+ logger.error(
f"Module {serialNumber} chip layout does not correspond to typical {pChipType} chip layouts. Please modify the trim values manually."
)
self.ChipGroupBoxDict.clear()
@@ -257,8 +257,8 @@ def makeChipBoxWithDB(self, pChipID, VDDA, VDDD, EfuseID="0", IREF="0"):
self.IREF = IREF
chip_iref_db[str(pChipID)] = str(IREF) # Store as string for easy comparison
- print(f"chip dict: {chip_iref_db}")
- print(f"Module Chip ID: {pChipID}, IREF: {self.IREF}")
+ logger.info(f"chip dict: {chip_iref_db}")
+ logger.info(f"Module Chip ID: {pChipID}, IREF: {self.IREF}")
if not self.ChipVDDDEdit.text():
logger.debug("no VDDD text")
@@ -366,7 +366,7 @@ def fetchHDIVersionFromDB(self, moduleName):
if match:
hdiversion = match.group(1).strip()
else:
- print("Warning: HDI version not found for module. Using default value of 1.")
+ logger.error("Warning: HDI version not found for module. Using default value of 1.")
hdiversion = "1"
return hdiversion
@@ -659,7 +659,7 @@ def onSerialNumberUpdate(self, module):
module.TypeCombo.setCurrentText(data["type"])
if module.HDIVersionCombo.isEnabled():
module.HDIVersionCombo.setCurrentText(data["HDIversion"])
- print('returning hdi version {0}'.format(data["HDIversion"]))
+ logger.info('returning hdi version {0}'.format(data["HDIversion"]))
self.updateList()
@@ -1291,7 +1291,7 @@ def getFirmwareDescription(self):
Module.getChips()[chipID].setCINJ(str(10 * float(chipData[chipID]["CINJ"])))
else:
- print(
+ logger.error(
"Something went wrong while fetching VDDD/VDDA from the database. Proceeding with default values."
)
diff --git a/Gui/python/Firmware.py b/Gui/python/Firmware.py
index 5c3d3a31..83bc1009 100644
--- a/Gui/python/Firmware.py
+++ b/Gui/python/Firmware.py
@@ -3,6 +3,8 @@
ModuleLaneMap_Dict,
)
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
class QtChip:
def __init__(
@@ -117,7 +119,7 @@ def getModuleName(self):
def setModuleType(self, moduleType: str):
if moduleType not in ModuleLaneMap.keys():
- print(
+ logger.error(
f"Module type '{moduleType}' is not familiar. Defaulting to 'CROC SCC'."
)
self.__moduleType = "CROC SCC"
diff --git a/Gui/python/IVCurveHandler.py b/Gui/python/IVCurveHandler.py
index 1cce0067..514e383c 100644
--- a/Gui/python/IVCurveHandler.py
+++ b/Gui/python/IVCurveHandler.py
@@ -40,7 +40,7 @@ def __init__(
# Making sure IVcurve peak is a negative voltage
if site_settings.IVcurve_range[testName] < 0:
self.stopVal = site_settings.IVcurve_range[testName]
- print("IVcurve range: ", self.stopVal)
+ logger.info("IVcurve range: ", self.stopVal)
else:
self.stopVal = -80
self.stepLength = 5
@@ -135,12 +135,12 @@ def run(self):
# "current": [value[2] for value in self.measurements['0']],
#}
- print("Voltages for channel {0}: ".format(channel), measurementStr["voltage"])
- print("Currents for channel {0}: ".format(channel), measurementStr["current"])
+ logger.info("Voltages for channel {0}: ".format(channel), measurementStr["voltage"])
+ logger.info("Currents for channel {0}: ".format(channel), measurementStr["current"])
self.measureSignal.emit("IVCurve", measurementList)
except Exception as e:
- print(f"IV Curve scan failed with error: {e}")
- print(traceback.format_exc())
+ logger.error(f"IV Curve scan failed with error: {e}")
+ logger.error(traceback.format_exc())
class IVCurveHandler(QObject):
measureSignal = pyqtSignal(str, object)
@@ -214,5 +214,5 @@ def stop(self):
)
self.test.terminate()
except Exception as err:
- print(f"Failed to stop the IV test due to error: {err}")
- print(traceback.format_exc())
+ logger.error(f"Failed to stop the IV test due to error: {err}")
+ logger.error(traceback.format_exc())
diff --git a/Gui/python/PSIColdbox.py b/Gui/python/PSIColdbox.py
index 93fc9c6c..e1e02bd9 100644
--- a/Gui/python/PSIColdbox.py
+++ b/Gui/python/PSIColdbox.py
@@ -3,6 +3,9 @@
import threading
import traceback
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
+
# Define monitoring payload types
payload_types = {
"Env": {
@@ -161,10 +164,10 @@ def __init__(self, host, topic="monTessie", error_callback=None):
def on_connect(self, client, userdata, flags, reason_code, properties=None):
"""Callback for successful connection."""
if reason_code == 0:
- print(f"Connected to {self.host} successfully.")
+ logger.info(f"Connected to {self.host} successfully.")
client.subscribe(self.topic)
else:
- print(
+ logger.error(
f"Failed to connect to {self.host}, reason code: {reason_code}. Retrying..."
)
@@ -172,7 +175,7 @@ def on_disconnect(
self, client, userdata, disconnect_flags, reason_code, properties=None
):
"""Callback for disconnection."""
- print(
+ logger.error(
f"Disconnected from {self.host}. Reason code: {reason_code}. Reconnecting..."
)
threading.Thread(target=self.reconnect, daemon=True).start()
@@ -181,13 +184,13 @@ def reconnect(self):
"""Reconnect to the MQTT broker."""
while True:
try:
- print(f"Attempting to reconnect to {self.host}...")
+ logger.info(f"Attempting to reconnect to {self.host}...")
self.client.reconnect()
- print(f"Successfully reconnected to {self.host}.")
+ logger.info(f"Successfully reconnected to {self.host}.")
break
except Exception as e:
- print(f"Reconnection failed: {e}. Retrying in 60 seconds...")
- print(traceback.format_exc())
+ logger.error(f"Reconnection failed: {e}. Retrying in 60 seconds...")
+ logger.info(traceback.format_exc())
time.sleep(60)
def on_message(self, client, userdata, msg):
@@ -213,9 +216,9 @@ def on_message(self, client, userdata, msg):
self.messages[key] = converted_payload[key]
except Exception as e:
- print(f"Failed to process message: {e}")
- print(f"payload = '{payload}'")
- print(traceback.format_exc())
+ logger.error(f"Failed to process message: {e}")
+ logger.error(f"payload = '{payload}'")
+ logger.error(traceback.format_exc())
def start(self):
"""Start the MQTT client."""
@@ -223,10 +226,10 @@ def start(self):
self.client.connect(self.host, 1883, 60)
self.client.loop_start()
except Exception as e:
- print(
+ logger.error(
f"Failed to connect to {self.host}: {e}. Retrying in the background..."
)
- print(traceback.format_exc())
+ logger.info(traceback.format_exc())
threading.Thread(target=self.reconnect, daemon=True).start()
def stop(self):
@@ -242,7 +245,7 @@ def get(self, key):
return self.messages[key]
if key not in payload_types:
- print("unknown key ", key)
+ logger.error("unknown key ", key)
return None
return None
@@ -299,9 +302,9 @@ def __init__(self, broker, topic="ctrlTessie"):
@staticmethod
def on_connect(client, userdata, flags, rc, properties=None):
if rc == 0:
- print("Connected to MQTT Broker!")
+ logger.info("Connected to MQTT Broker!")
else:
- print("Failed to connect, return code %d\n", rc)
+ logger.error("Failed to connect, return code %d\n", rc)
def _connect_mqtt(self):
# Set Connecting Client ID
@@ -331,7 +334,7 @@ def on_message(client, userdata, msg_recv):
if msg_recv.payload.decode().startswith("help"):
return
if msg_recv.payload.decode().startswith(">"):
- print(msg_recv.payload.decode())
+ logger.info(msg_recv.payload.decode())
return
# print('recv: ' + msg_recv.payload.decode())
Tessie.decode_msg(msg_recv.payload.decode())
@@ -358,13 +361,13 @@ def get(self, var, args="") -> str:
Tessie.waiting.append(var)
# print('send ' + msg)
if self._client.publish(self.topic, msg)[0] != 0:
- print(f"Failed to send message: {msg}")
+ logger.error(f"Failed to send message: {msg}")
result = Tessie._wait_for_var(var)
if not result:
- print("no result")
+ logger.info("no result")
return False
if not result.startswith(var):
- print("wrong result")
+ logger.info("wrong result")
return False
result = result[len(var) + 3 :]
# print(result)
@@ -374,7 +377,7 @@ def set(self, var, data, args=""):
msg = "set " + str(var) + " " + str(data) + args
# print('send ' + msg)
if self._client.publish(self.topic, msg)[0] != 0:
- print(f"Failed to send message: {msg}")
+ logger.error(f"Failed to send message: {msg}")
def cmd(self, cmd, args="", answer=False):
msg = "cmd " + cmd + args
@@ -382,14 +385,14 @@ def cmd(self, cmd, args="", answer=False):
if answer:
Tessie.waiting.append(cmd)
if self._client.publish(self.topic, msg)[0] != 0:
- print(f"Failed to send message: {msg}")
+ logger.error(f"Failed to send message: {msg}")
if answer:
result = Tessie._wait_for_var(cmd)
if not result:
- print("no result")
+ logger.info("no result")
return False
if not result.startswith(cmd):
- print("wrong result")
+ logger.info("wrong result")
return False
result = result[len(cmd) + 3 :]
# print(result)
@@ -398,7 +401,7 @@ def cmd(self, cmd, args="", answer=False):
def help(self):
msg = "help"
if self._client.publish(self.topic, msg)[0] != 0:
- print(f"Failed to send message: {msg}")
+ logger.error(f"Failed to send message: {msg}")
class Valve:
@@ -607,7 +610,7 @@ def channel_arg(self, arg, caller=""):
):
return arg
else:
- print("Coldbox.{caller} : invalid channel argument ", arg)
+ logger.error("Coldbox.{caller} : invalid channel argument ", arg)
return []
# pass-through functions for data available in the control topic
@@ -662,7 +665,7 @@ def flush(self, cmd="flush"):
def get_monitor_data(self, key, timeout=0):
"""get data from the monitor topic"""
if key not in payload_types:
- print("unknown key ", key)
+ logger.error("unknown key ", key)
return None
for ntry in range(timeout + 1):
@@ -741,10 +744,10 @@ def _tec_get_property(self, channel, key):
tec = self._tecs[channel]
return tec._single(tec._tessie.get(key, tec.name))
else:
- print("unknown channel ", channel)
+ logger.error("unknown channel ", channel)
return None
else:
- print("unknown tec property", key)
+ logger.error("unknown tec property", key)
return None
def get_tec_state(self, channel=0):
@@ -764,7 +767,7 @@ def get_voltage_probe(self, channel):
for single channels only, channel must be an integer from [1..8]
"""
if channel not in self.valid_channels:
- print("Coldbox.get_voltage_probe : invalid channel ", channel)
+ logger.error("Coldbox.get_voltage_probe : invalid channel ", channel)
return None
vprobe_names = [
@@ -792,8 +795,8 @@ def handle_error_message(error_payload):
Custom callback to handle "Error" messages.
:param error_payload: The parsed "Error" payload
"""
- print("WARNING: Error detected!")
- print(error_payload)
+ logger.error("WARNING: Error detected!")
+ logger.error(error_payload)
if __name__ == "__main__":
@@ -802,23 +805,23 @@ def handle_error_message(error_payload):
with coldbox:
coldbox.flush()
- print("air temperature ", coldbox.get_air_temperature())
- print("water temperature ", coldbox.get_water_temperature())
- print("interlock status ", coldbox.get_interlock_status(timeout=10))
- print("traffic light ", coldbox.get_traffic_light())
- print("flow switch ", coldbox.get_flow_switch())
- print("lid ", coldbox.get_lid_status())
+ logger.info("air temperature ", coldbox.get_air_temperature())
+ logger.info("water temperature ", coldbox.get_water_temperature())
+ logger.info("interlock status ", coldbox.get_interlock_status(timeout=10))
+ logger.info("traffic light ", coldbox.get_traffic_light())
+ logger.info("flow switch ", coldbox.get_flow_switch())
+ logger.info("lid ", coldbox.get_lid_status())
channel = 8
- print(
+ logger.info(
f"voltage probes for channel {channel} = ",
coldbox.get_voltage_probe(channel),
)
try:
while True:
- print("relative humidity ", coldbox.get_relative_humidity())
+ logger.info("relative humidity ", coldbox.get_relative_humidity())
sleep(10)
except KeyboardInterrupt:
- print("interrupted!")
+ logger.error("interrupted!")
- print("shutting down")
+ logger.info("shutting down")
diff --git a/Gui/python/Peltier.py b/Gui/python/Peltier.py
index 76a0732b..83a41e48 100644
--- a/Gui/python/Peltier.py
+++ b/Gui/python/Peltier.py
@@ -118,8 +118,8 @@ def sendCommand(self, command):
logger.debug(f"Recieved message: {message}")
return message, passed
except Exception as e:
- print(f"Failed to send command to Peltier due to error: {e}")
- print(traceback.format_exc())
+ logger.error(f"Failed to send command to Peltier due to error: {e}")
+ logger.error(traceback.format_exc())
return None, False
# Will recieve message but will only check if the command gave an error, will not decode the message
diff --git a/Gui/python/ROOTInterface.py b/Gui/python/ROOTInterface.py
index ac5af604..51aa9c1c 100644
--- a/Gui/python/ROOTInterface.py
+++ b/Gui/python/ROOTInterface.py
@@ -51,7 +51,7 @@ def GetDirectory(inputFile):
try:
openFile = ROOT.TFile.Open(inputFile, "READ")
except IOError:
- print("File: {0} not opened".format(inputFile))
+ logger.error("File: {0} not opened".format(inputFile))
ListOfRoots = openFile.GetListOfKeys()
@@ -69,7 +69,7 @@ def GetDirectory(inputFile):
def DirectoryVLR(node, depth):
nodeName = "-" * depth + node.getKeyName()
- print(nodeName + ";" + node.getClassName())
+ logger.info(nodeName + ";" + node.getClassName())
if node.getClassName() == "TCanvas":
obj = node.getObject()
obj.SetBatch(ROOT.kTRUE)
diff --git a/Gui/python/ResultTreeWidget.py b/Gui/python/ResultTreeWidget.py
index 1b3d78d7..fec9929a 100644
--- a/Gui/python/ResultTreeWidget.py
+++ b/Gui/python/ResultTreeWidget.py
@@ -307,10 +307,10 @@ def updateSLDOResult(self, sourceFolder):
stepFiles2 = process2.stdout.decode("utf-8").rstrip("\n").split("\n")
if stepFiles2 == [""]:
- print("No SLD files found.") # Debugging output if no SLD files are found
+ logger.debug("No SLD files found.") # Debugging output if no SLD files are found
return
- print(
+ logger.debug(
"SLD files found:", stepFiles2
) # Debugging output to show the found SLD files
@@ -321,7 +321,7 @@ def updateSLDOResult(self, sourceFolder):
CurrentNode.setText(0, File.split("/")[-1])
CurrentNode.setData(0, Qt.UserRole, File)
self.TreeRoot.addChild(CurrentNode)
- print(
+ logger.info(
"SLD files processed."
) # Debugging output to indicate SLD files processing is done
diff --git a/Gui/python/RootDataExtractor.py b/Gui/python/RootDataExtractor.py
index 786c38c8..4d7f3f6e 100644
--- a/Gui/python/RootDataExtractor.py
+++ b/Gui/python/RootDataExtractor.py
@@ -1,9 +1,10 @@
import ROOT
import os
from ctypes import c_double
-from Gui.python.logging_config import logger
+from Gui.python.logging_config import get_logger
import traceback
+logger = get_logger(__name__)
def extract_data_from_root(root_file_path, chip, measurement_type):
"""
@@ -18,7 +19,7 @@ def extract_data_from_root(root_file_path, chip, measurement_type):
dict: A dictionary containing the extracted data.
"""
if not os.path.exists(root_file_path):
- print(f"ROOT file not found: {root_file_path}")
+ logger.error(f"ROOT file not found: {root_file_path}")
return None
try:
@@ -26,7 +27,7 @@ def extract_data_from_root(root_file_path, chip, measurement_type):
# Open the ROOT file
root_file = ROOT.TFile(root_file_path, "READ")
if root_file.IsZombie():
- print(f"Failed to open ROOT file: {root_file_path}")
+ logger.error(f"Failed to open ROOT file: {root_file_path}")
return None
# Construct the path to the desired data
@@ -35,7 +36,7 @@ def extract_data_from_root(root_file_path, chip, measurement_type):
# Retrieve the TGraph object
tgraph = root_file.Get(detector_path)
if not tgraph:
- print(f"TGraph not found at path: {detector_path}")
+ logger.error(f"TGraph not found at path: {detector_path}")
root_file.Close()
return None
@@ -63,4 +64,4 @@ def extract_data_from_root(root_file_path, chip, measurement_type):
measurement_type = "VDDA"
data = extract_data_from_root(root_file, chip, measurement_type)
if data:
- print(f"Extracted data for chip {chip}, measurement {measurement_type}: {data}")
+ logger.info(f"Extracted data for chip {chip}, measurement {measurement_type}: {data}")
diff --git a/Gui/python/SLDOScanHandler.py b/Gui/python/SLDOScanHandler.py
index 57aaee45..d4f14a4e 100644
--- a/Gui/python/SLDOScanHandler.py
+++ b/Gui/python/SLDOScanHandler.py
@@ -180,19 +180,19 @@ def runWithADC(self) -> None:
self.measure.emit(VDDDresults, "VDDD_ROC{0}".format(chip), "GADC")
self.measure.emit(VDDAresults, "VDDA_ROC{0}".format(chip), "GADC")
- print("LV Voltages Up: {0}\nLV Voltages Down: {1}".format(
+ logger.info("LV Voltages Up: {0}\nLV Voltages Down: {1}".format(
LV_Voltage_Up, LV_Voltage_Down
))
- print("Pin map used: {0}".format(self.adc_board._pin_map))
+ logger.info("Pin map used: {0}".format(self.adc_board._pin_map))
for name in self.adc_board._pin_map.values():
if index != pin10index:
- print('the name of the pin is {0}'.format(name))
+ logger.info('the name of the pin is {0}'.format(name))
ADC_Voltage_Up = [res[index] for res in data_up]
result_up = np.array([Currents_Up, LV_Voltage_Up, ADC_Voltage_Up])
ADC_Voltage_Down = [res[index] for res in data_down]
result_down = np.array([Currents_Down, LV_Voltage_Down, ADC_Voltage_Down])
- print("ADC Voltages Up: {0}\nADC Voltages Down: {1}".format(
+ logger.info("ADC Voltages Up: {0}\nADC Voltages Down: {1}".format(
ADC_Voltage_Up, ADC_Voltage_Down))
index += 1
else:
@@ -359,7 +359,7 @@ def stop(self, reason=None):
# Should only have a reason internally where the abort signal is necessary.
# External calls can handle abort themselves. Avoiding accidental recursion.
if reason:
- print(f"Aborting SLDO Scan. Reason: {reason}")
+ logger.error(f"Aborting SLDO Scan. Reason: {reason}")
try:
starting_voltages = [
np.abs(getattr(module["hv"], "voltage"))
diff --git a/Gui/python/SimplifiedMainWidget.py b/Gui/python/SimplifiedMainWidget.py
index 649eaf63..cab5d3fa 100644
--- a/Gui/python/SimplifiedMainWidget.py
+++ b/Gui/python/SimplifiedMainWidget.py
@@ -183,7 +183,7 @@ def setupPeltier(self):
self.peltier_temperature_label = QLabel(self)
except Exception as e:
- print("Error while attempting to set Peltier", e)
+ logger.error("Error while attempting to set Peltier", e)
logger.error(traceback.format_exc())
self.Peltier = None
@@ -426,11 +426,11 @@ def runNewTest(self):
module_type = module.getModuleType()
self.master.module_in_use = module_type
- print("Firmware Description")
+ logger.info("Firmware Description")
for beboard in self.firmwareDescription:
- print(beboard)
+ logger.info(beboard)
- print("Firmware Check")
+ logger.info("Firmware Check")
for beboard in self.firmwareDescription:
SummaryBox.checkFwPar(
beboard.getBoardName(), module_type, beboard.getIPAddress()
@@ -705,7 +705,7 @@ def run(self):
time.sleep(self.delay)
def abort_worker(self):
- print("Worker aborted")
+ logger.info("Worker aborted")
self.abort = True
diff --git a/Gui/python/TestHandler.py b/Gui/python/TestHandler.py
index 8c0c2613..ea8a57ef 100644
--- a/Gui/python/TestHandler.py
+++ b/Gui/python/TestHandler.py
@@ -185,10 +185,10 @@ def __init__(self, runwindow, master, info, firmware, txt_files={}):
}
self.finished_tests = []
self.Ph2_ACF_ver = os.environ.get("PH2ACF_VERSION")
- print("Using version {0} of Ph2_ACF".format(self.Ph2_ACF_ver))
+ logger.info("Using version {0} of Ph2_ACF".format(self.Ph2_ACF_ver))
#self.firmwareImage = firmware_image[self.ModuleType][self.Ph2_ACF_ver]
self.firmwareImage = firmware_image[self.ModuleType]
- print("Firmware version is {0}".format(self.firmwareImage))
+ logger.info("Firmware version is {0}".format(self.firmwareImage))
self.RunNumber = "-1"
self.isTDACtuned = False
@@ -339,7 +339,7 @@ def initializeRD53Dict(self):
] = None
fwPath = "{0}_{1}_{2}".format(beboardId, ogId, moduleId)
self.ModuleMap[fwPath] = moduleName
- print("module map is {0}:{1}".format(fwPath, self.ModuleMap[fwPath]))
+ logger.info("module map is {0}:{1}".format(fwPath, self.ModuleMap[fwPath]))
def config_output_dir(self, testName):
ModuleIDs = []
@@ -424,7 +424,7 @@ def configTest(self, **kwargs):
) + "/settings/RD53Files/CMSIT_{0}{1}.txt".format(
self.boardType, self.moduleVersion
)
- print("Getting config file {0}".format(self.rd53_file[key]))
+ logger.info("Getting config file {0}".format(self.rd53_file[key]))
# At first there should be no input_dir and we should be grabbing the default txt files.
# After the first test, we should see values or input_dir and output_dir signifiying that the txt files are being updated.
@@ -437,7 +437,7 @@ def configTest(self, **kwargs):
SetupRD53ConfigfromFile(self.rd53_file, self.output_dir)
else:
logger.debug(f"{self.testIndexTracker=}")
- print(os.listdir(self.input_dir))
+ logger.debug(os.listdir(self.input_dir))
SetupRD53Config(self.input_dir, self.output_dir, self.rd53_file)
# NOTE: This code block is used to generate the XML configuration files
@@ -608,7 +608,7 @@ def GADC_execute_each_step(
]["starting current"]
):
continue
- print(f"Beginning physics test at {voltage}V and {current}A")
+ logger.info(f"Beginning physics test at {voltage}V and {current}A")
self.outputString.emit(
f"Beginning physics test at {voltage}V and {current}A",
self.runwindow.ConsoleViews[fc7_index],
@@ -676,7 +676,7 @@ def runSingleTest(self, testName, nextTest=None):
].setValue(100)
return
- print("Executing Single Step test...")
+ logger.debug("Executing Single Step test...")
for console in self.runwindow.ConsoleViews:
self.outputString.emit("Executing Single Step test...", console)
@@ -808,7 +808,7 @@ def runSingleTest(self, testName, nextTest=None):
].values()
],
]
- print(data)
+ logger.info(data)
self.makeSLDOPlot(data, f"{datatype}_ROC{int(chip)}", "GADC")
self.makeSLDOPlot(data, f"{datatype}_ROC{int(chip)}", "GADC")
@@ -818,7 +818,7 @@ def runSingleTest(self, testName, nextTest=None):
if self.instruments:
lv_on = False
for number in self.instruments.get_modules().keys():
- print(self.instruments.status()[number]["lv"])
+ logger.info(self.instruments.status()[number]["lv"])
if self.instruments.status()[number]["lv"]:
lv_on = True
break
@@ -900,7 +900,7 @@ def runSingleTest(self, testName, nextTest=None):
if not hv_status:
self.instruments.hv_on(voltage=0, delay=0.5, step_size=10, no_lock=True)
self.powergroup.enable_all()
- print("trying to turn on HV")
+ logger.debug("trying to turn on HV")
self.powergroup.ramp_hv(
voltage=default_hv_voltage,
delay=0.3,
@@ -958,7 +958,7 @@ def setupQProcess(self):
# Check if the test was aborted
if self.halt:
- print("Test aborted. Skipping QProcess setup.")
+ logger.debug("Test aborted. Skipping QProcess setup.")
return
for process in self.info_processes:
process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
@@ -1222,7 +1222,7 @@ def validateTest(self):
for OG in beboard.getAllOpticalGroups().values():
ogID = OG.getOpticalGroupID()
for module in OG.getAllModules().values():
- print(f"curr test {self.currentTest}")
+ logger.info(f"curr test {self.currentTest}")
hybridID = module.getFMCPort()
module_data = {
"boardID": boardID,
@@ -1287,7 +1287,7 @@ def collect_plots(self, moduleName, felis_instance=None):
else:
return []
else:
- print("testHandler.collect_plots Exception:", repr(e))
+ logger.error("testHandler.collect_plots Exception:", repr(e))
return []
else:
@@ -1384,7 +1384,7 @@ def saveTest(self, processIndex: int, process: QProcess):
elif "IVCurve" in self.currentTest:
- print("copying MonitorDQM.root file to output directory")
+ logger.debug("copying MonitorDQM.root file to output directory")
current_fc7: str = self.firmware[processIndex].getBoardName()
@@ -1415,7 +1415,7 @@ def saveTest(self, processIndex: int, process: QProcess):
)
elif "IREF_GADC" in self.currentTest:
- print("copying MonitorDQM.root file to output directory")
+ logger.debug("copying MonitorDQM.root file to output directory")
current_fc7: str = self.firmware[processIndex].getBoardName()
os.system(
"cp {0}/test/Results/Run{1}_MonitorDQM_Board_{2}*.root {3}/".format( #Chaneged from {0}/test/Results/Run{1}_MonitorDQM_Board_{2}*.root {3}
@@ -1462,7 +1462,7 @@ def saveTest(self, processIndex: int, process: QProcess):
@QtCore.pyqtSlot()
def on_readyReadStandardOutput(self, processIndex: int):
if self.readingOutput:
- print("Thread competition detected")
+ logger.error("Thread competition detected")
return
self.readingOutput = True
@@ -1497,7 +1497,7 @@ def on_readyReadStandardOutput(self, processIndex: int):
chip_number = clean_text.split("RD53: ")[-1].strip()
self.fused_dict_index[1] = chip_number
# print(f"Clean_text: {clean_text}")
- print(f"Chip Number: {chip_number}")
+ logger.info(f"Chip Number: {chip_number}")
if self._openBumpTest_running:
if self._OBT_starttime is None:
@@ -1540,7 +1540,7 @@ def on_readyReadStandardOutput(self, processIndex: int):
].setValue(self.ProgressValue)
except Exception as e:
- print(f"Error while updating progress bar {e}")
+ logger.error(f"Error while updating progress bar {e}")
logger.error(traceback.format_exc())
pass
@@ -1692,7 +1692,7 @@ def on_readyReadStandardOutput(self, processIndex: int):
self.readingOutput = False
def updateOptimizedXMLValues(self):
- print("trying to update the xml value")
+ logger.debug("trying to update the xml value")
try:
if Test_to_Ph2ACF_Map[self.currentTest] in optimizationTestMap.keys():
updatedFEKeys = optimizationTestMap[
@@ -1778,7 +1778,7 @@ def on_readyReadStandardOutput_VDDsweep(self, process, fc7_index):
Safe to use in TestHandler as long as updateConsoleInfo does not emit outputString.
"""
if getattr(self, "readingOutput", False):
- print("Thread competition detected")
+ logger.warning("Thread competition detected")
return
self.readingOutput = True
@@ -1833,7 +1833,7 @@ def on_readyReadStandardOutput_GADC(
self, process: QProcess, fc7_index: int, upOrDown: str, current, channel
):
if self.readingOutput:
- print("Thread competition detected")
+ logger.warning("Thread competition detected")
return
self.readingOutput = True
@@ -1905,7 +1905,7 @@ def on_readyReadStandardOutput_GADC(
) # This line enforces that it only logs one VDDD or VDDA value per sweep step
else:
- print(
+ logger.error(
f'Error: Did not receive expected message, "Reading monitored data for \
[board/opticalGroup/hybrid/chip = ...]", before measurement message "{match.group(0)}"'
)
@@ -1963,7 +1963,7 @@ def on_finish(self, processIndex: int):
# Finished all subtests
self.currentTest = "OpenBumpTest"
logger.info("All OpenBumpTest subtests finished. Validating...")
- print(f"Current openbumptest subtest index = {self._openBumpTest_subtest_index}")
+ logger.info(f"Current openbumptest subtest index = {self._openBumpTest_subtest_index}")
self._openBumpTest_running = False
# Ensure that all processes have finished before continuing
@@ -2031,7 +2031,7 @@ def onFinalTest(self, index):
"module": module,
}
index -= 1
- print(
+ logger.info(
f"self.BBanalysis_root_files: {self.BBanalysis_root_files}")
self.felis_instances[fc7_index].set_result(
self.BBanalysis_root_files,
@@ -2163,8 +2163,8 @@ def makeTrimbitScanPlots(self, trimbit_dict, pin_mapping):
# Filter out invalid data
trimbits = np.array(trimbits, dtype=float)
values = np.array(values, dtype=float)
- print(f"Trimbits: {trimbits}")
- print(f"Values: {values}")
+ logger.info(f"Trimbits: {trimbits}")
+ logger.info(f"Values: {values}")
valid_indices = ~np.isnan(values)
trimbits = trimbits[valid_indices]
values = values[valid_indices]
diff --git a/Gui/python/TestValidator.py b/Gui/python/TestValidator.py
index 38af6d4c..0dcc2b7e 100644
--- a/Gui/python/TestValidator.py
+++ b/Gui/python/TestValidator.py
@@ -122,7 +122,7 @@ def ResultGrader(
dqmpattern = re.compile(rf"_Hybrid_{module_hybridID}\.root$")
relevant_files.extend([outputDir + "/" + os.fsdecode(file) for file in os.listdir(outputDir) if dqmpattern.search(file)])
- print("relevant_files:", relevant_files)
+ logger.debug("relevant_files:", relevant_files)
_1, _2 = felis.set_module(
name_module = module_name,
subdetector = module_type.split(" ")[0],
diff --git a/Gui/python/rhapi.py b/Gui/python/rhapi.py
index 391ef4f0..7f4b0b2a 100644
--- a/Gui/python/rhapi.py
+++ b/Gui/python/rhapi.py
@@ -18,6 +18,9 @@
from requests.utils import requote_uri
import time
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()
# warnings.filterwarnings("error")
@@ -296,7 +299,7 @@ def _action(self, action, url, headers, data):
raise Exception('Error while logging to HTTPS/SSO')
if r.status_code == 503 or r.status_code == 502 or r.status_code == 500:
- print("waiting for response... likely resthub is restarting")
+ logger.error("waiting for response... likely resthub is restarting")
time.sleep(20)
with warnings.catch_warnings():
r = action(url=url, headers=headers, data=data, cookies=cookies, verify=False)
@@ -309,10 +312,10 @@ def dprint(self, *args):
Print debug information
"""
if self.debug:
- print("RhApi:", end='')
+ logger.debug("RhApi:", end='')
for arg in args:
- print(arg, end='')
- print()
+ logger.debug(arg, end='')
+ logger.debug()
def get(self, parts, data=None, headers=None, params=None, verbose=False, cols=False, inline_clobs=False,
method=None):
@@ -502,10 +505,10 @@ def data1(self, query, params=None, form='text/csv', pagesize=None, page=None, v
except Exception as e:
err_msg = str(e)
if (attempt < 4) and ("Query ID" in err_msg):
- print("failing to fetch query id attemp num:",attempt)
+ logger.error("failing to fetch query id attemp num:",attempt)
time.sleep(20)
else:
- print("Inform the developer of this condition with error logs")
+ logger.error("Inform the developer of this condition with error logs")
raise e
@@ -774,7 +777,7 @@ def run(self):
if options.count:
- print(api.count(api.qid(arg), params=params, verbose=options.verbose))
+ logger.info(api.count(api.qid(arg), params=params, verbose=options.verbose))
elif options.histo:
@@ -797,16 +800,16 @@ def run(self):
verbose=options.verbose)
if options.format in ['json', 'json2']:
- print(histo)
+ logger.info(histo)
else:
- print('\t'.join(histo['cols']))
+ logger.info('\t'.join(histo['cols']))
for b in histo['bins']:
- print('\t'.join([str(n) for n in b]))
+ logger.info('\t'.join([str(n) for n in b]))
elif options.metadata:
qid = api.qid(arg)
- print(self.pprint(api.query(qid, verbose=options.verbose)))
+ logger.info(self.pprint(api.query(qid, verbose=options.verbose)))
else:
@@ -822,7 +825,7 @@ def run(self):
if options.format == 'csv':
try:
- print(api.csv(arg, params=params, pagesize=options.size, page=options.page,
+ logger.info(api.csv(arg, params=params, pagesize=options.size, page=options.page,
verbose=options.verbose, inline_clobs=options.inclob))
except RhApiRowLimitError as e:
if options.all:
@@ -832,28 +835,28 @@ def run(self):
res = api.csv(arg, params=params, pagesize=e.rowsLimit, page=page,
verbose=options.verbose, inline_clobs=options.inclob)
if page == 1:
- print(res, end='')
+ logger.info(res, end='')
else:
- print('\n'.join(res.split('\n')[1:]), end='')
+ logger.info('\n'.join(res.split('\n')[1:]), end='')
else:
raise e
if options.format == 'xml':
try:
- print(api.xml(arg, params=params, pagesize=options.size, page=options.page,
+ logger.info(api.xml(arg, params=params, pagesize=options.size, page=options.page,
verbose=options.verbose, inline_clobs=options.inclob))
except RhApiRowLimitError as e:
if options.all:
page = 0
- print('', end='')
+ logger.info('', end='')
while (page * e.rowsLimit) < e.count:
page = page + 1
res = api.xml(arg, params=params, pagesize=e.rowsLimit, page=page,
verbose=options.verbose, inline_clobs=options.inclob)
root = minidom.parseString(res).documentElement
for row in root.getElementsByTagName('row'):
- print(row.toxml(), end='')
- print('')
+ logger.info(row.toxml(), end='')
+ logger.info('')
else:
raise e
@@ -882,7 +885,7 @@ def run(self):
if options.format == 'root':
self._to_root(data, options.root)
else:
- print(data)
+ logger.info(data)
return 0
@@ -890,15 +893,15 @@ def run(self):
except RhApiRowLimitError as e:
- print("ERROR: %s\nDetails: %s, consider --all option" % (type(e).__name__, e))
+ logger.error("ERROR: %s\nDetails: %s, consider --all option" % (type(e).__name__, e))
except requests.exceptions.RequestException as e:
reason = e.reason if hasattr(e, 'reason') else '%s' % e
- print("ERROR: %s\nDetails: %s" % (reason, e))
+ logger.error("ERROR: %s\nDetails: %s" % (reason, e))
except Exception as e:
- print("ERROR: %s\nDetails: %s" % (type(e).__name__, e))
+ logger.error("ERROR: %s\nDetails: %s" % (type(e).__name__, e))
import traceback
traceback.print_exc()
@@ -951,9 +954,9 @@ def _to_root(self, data, filename):
try:
setattr(row, c['name'], v)
except Exception as e:
- print(c['name'], '=', v)
- print(c, v)
- print(e)
+ logger.error(c['name'], '=', v)
+ logger.error(c, v)
+ logger.error(e)
tree.Fill()
tree.Print()
diff --git a/logs/Ph2_ACF.log b/logs/Ph2_ACF.log
deleted file mode 100644
index ff36ef38..00000000
--- a/logs/Ph2_ACF.log
+++ /dev/null
@@ -1,34 +0,0 @@
-15.04.2021 13:21 ||I| CMS Ph2_ACF Data acquisition test and Data dump
-
-Available options
------------------
--h, --help
- Print this help page
-
--l, --list
- Print the list of available firmware images on SD card (works only with
- CTA boards)
-
--d , --delete
- Delete a firmware image on SD card (works only with CTA boards)
-
--f , --file
- Local FPGA Bitstream file (*.mcs format for GLIB or *.bit/*.bin format for
- CTA boards)
-
---download , -o
- Download an FPGA configuration from SD card to file (only for CTA boards)
-
--c , --config
- Hw Description File . Default value: settings/HWDescription_2CBC.xml
-
--i , --image
- Without -f: load image from SD card to FPGA
- With -f: name of image written to SD card
- -f specifies the source filename
-
-Return codes
------------------
- 0 Success
- 1 Error
-
diff --git a/logs/Ph2_ACF_debug.log b/logs/Ph2_ACF_debug.log
deleted file mode 100644
index e69de29b..00000000
diff --git a/logs/Ph2_ACF_err.log b/logs/Ph2_ACF_err.log
deleted file mode 100644
index e69de29b..00000000
diff --git a/logs/Ph2_ACF_warn.log b/logs/Ph2_ACF_warn.log
deleted file mode 100644
index e69de29b..00000000
diff --git a/logs/myeasylog.log b/logs/myeasylog.log
deleted file mode 100644
index e69de29b..00000000
diff --git a/tests/data/#test_TestHandler.py# b/tests/data/#test_TestHandler.py#
index 44272027..be201481 100644
--- a/tests/data/#test_TestHandler.py#
+++ b/tests/data/#test_TestHandler.py#
@@ -1,5 +1,7 @@
from unittest.mock import MagicMock
from Gui.TestHandler import TestHandler
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
####################
@@ -42,4 +44,4 @@ if __name__ == "__main__":
match = re.search(r"Configuring chips of hybrid: (\d+)$", line)
if match:
- print(match.group(1)) # Output: 0
+ logger.info(match.group(1)) # Output: 0
diff --git a/tests/data/test.py b/tests/data/test.py
index 63488c89..b1a37bb6 100644
--- a/tests/data/test.py
+++ b/tests/data/test.py
@@ -1,7 +1,9 @@
import re
+from Gui.python.logging_config import get_logger
+logger = get_logger(__name__)
line = "|06:25:13|I|>>> Progress: 0.3% <<<"
match = re.search(r"Progress:\s+([0-9]*\.?[0-9]+)%", line)
if match:
- print(type(match.group(1))) # Output: 0.3
+ logger.info(type(match.group(1))) # Output: 0.3