Salome HOME
Change log directory. It is now set in site.pyconf
[tools/sat.git] / src / logger.py
index 9b0135d3ca72a18d2d27d15bc16bcc6ba8623646..24b234ab86fc0a72721e48bd25ebd4bfb583a1c0 100644 (file)
@@ -25,7 +25,7 @@ from . import printcolors
 from . import xmlManager
 
 class Logger(object):
-    '''Class that handle log mechanism
+    '''Class to handle log mechanism
     '''
     def __init__(self, config, silent_sysstd=False):
         '''Initialization
@@ -39,26 +39,34 @@ class Logger(object):
         
         # Construct log file location. There are two cases. With an application an without any application.
         logFileName = config.VARS.datehour + "_" + config.VARS.command + ".xml"
-        if 'APPLICATION' in config:
-            logFilePath = os.path.join(config.APPLICATION.out_dir, 'LOGS', logFileName)
-        else:
-            logFilePath = os.path.join(config.VARS.personalDir, 'LOGS', logFileName)
+        logFilePath = os.path.join(config.SITE.log.logDir, logFileName)
+
         src.ensure_path_exists(os.path.dirname(logFilePath))
         
         self.logFileName = logFileName
         self.logFilePath = logFilePath   
-        
-        self.xmlFile = xmlManager.xmlLogFile(logFilePath, config.VARS.command)
+        self.xmlFile = xmlManager.xmlLogFile(logFilePath, "SATcommand", attrib = {"command" : config.VARS.command})
         self.putInitialXMLFields()
         
     def putInitialXMLFields(self):
-        self.xmlFile.add_simple_node("field", text=self.config.VARS.command , attrib={"name" : "command"})
-        self.xmlFile.add_simple_node("field", text=self.config.INTERNAL.sat_version , attrib={"name" : "satversion"})
-        self.xmlFile.add_simple_node("field", text=self.config.VARS.hostname , attrib={"name" : "hostname"})
-        self.xmlFile.add_simple_node("field", text=self.config.VARS.dist , attrib={"name" : "OS"})
-        self.xmlFile.add_simple_node("field", text=self.config.VARS.user , attrib={"name" : "user"})
-        self.xmlFile.add_simple_node("field", text=self.config.VARS.datehour , attrib={"name" : "beginTime"})
-        self.xmlFile.add_simple_node("traces",text="")
+        '''Method called at class initialization : Put all fields corresponding to the command context (user, time, ...)
+        '''
+        # command name
+        self.xmlFile.add_simple_node("Site", attrib={"command" : self.config.VARS.command})
+        # version of salomeTools
+        self.xmlFile.append_node_attrib("Site", attrib={"satversion" : self.config.INTERNAL.sat_version})
+        # machine name on which the command has been launched
+        self.xmlFile.append_node_attrib("Site", attrib={"hostname" : self.config.VARS.hostname})
+        # Distribution of the machine
+        self.xmlFile.append_node_attrib("Site", attrib={"OS" : self.config.VARS.dist})
+        # The user that have launched the command
+        self.xmlFile.append_node_attrib("Site", attrib={"user" : self.config.VARS.user})
+        # The time when command was launched
+        Y, m, dd, H, M, S = date_to_datetime(self.config.VARS.datehour)
+        date_hour = "%2s/%2s/%4s %2sh%2sm%2ss" % (dd, m, Y, H, M, S)
+        self.xmlFile.append_node_attrib("Site", attrib={"beginTime" : date_hour})
+        # The initialization of the trace node
+        self.xmlFile.add_simple_node("Log",text="")
 
     def write(self, message, level=None, screenOnly=False):
         '''the function used in the commands that will print in the terminal and the log file.
@@ -69,7 +77,7 @@ class Logger(object):
         '''
         # do not write message starting with \r to log file
         if not message.startswith("\r") and not screenOnly:
-            self.xmlFile.append_node("traces", printcolors.cleancolor(message))
+            self.xmlFile.append_node_text("Log", printcolors.cleancolor(message))
 
         # get user or option output level
         current_output_level = self.config.USER.output_level
@@ -92,7 +100,7 @@ class Logger(object):
         :param message str: The message to print.
         '''
         # Print in the log file
-        self.xmlFile.append_node("traces", _('ERROR:') + message)
+        self.xmlFile.append_node_text("traces", _('ERROR:') + message)
 
         # Print in the terminal and clean colors if the terminal is redirected by user
         if not ('isatty' in dir(sys.stderr) and sys.stderr.isatty()):
@@ -105,25 +113,59 @@ class Logger(object):
         '''
         sys.stdout.flush()
         
-    def endWrite(self):
+    def endWrite(self, attribute):
+        '''Method called just after command end : Put all fields corresponding to the command end context (time).
+        Write the log xml file on the hard drive.
+        And display the command to launch to get the log
+        
+        :param attribute dict: the attribute to add to the node "Site".
+        '''       
+        # Get current time (end of command) and format it
         dt = datetime.datetime.now()
-        endtime = dt.strftime('%Y%m%d_%H%M%S')
-        t0 = date_to_datetime(self.config.VARS.datehour)
+        Y, m, dd, H, M, S = date_to_datetime(self.config.VARS.datehour)
+        t0 = datetime.datetime(int(Y), int(m), int(dd), int(H), int(M), int(S))
         tf = dt
         delta = tf - t0
-        total_time = delta.total_seconds()
+        total_time = timedelta_total_seconds(delta)
         hours = int(total_time / 3600)
         minutes = int((total_time - hours*3600) / 60)
         seconds = total_time - hours*3600 - minutes*60
-        self.xmlFile.add_simple_node("field", text=endtime , attrib={"name" : "endTime"})
-        self.xmlFile.add_simple_node("field", text="%ih%im%is" % (hours, minutes, seconds) , attrib={"name" : "Total Time"})
+        # Add the fields corresponding to the end time and the total time of command
+        endtime = dt.strftime('%d/%Y/%m %Hh%Mm%Ss')
+        self.xmlFile.append_node_attrib("Site", attrib={"endTime" : endtime})
+        self.xmlFile.append_node_attrib("Site", attrib={"TotalTime" : "%ih%im%is" % (hours, minutes, seconds)})
+        
+        # Add the attribute passed to the method
+        self.xmlFile.append_node_attrib("Site", attrib=attribute)
+        
+        # Call the method to write the xml file on the hard drive
         self.xmlFile.write_tree(stylesheet = "command.xsl")
+        
+        # Update the hat xml (that shows all logs) in order to make the new log visible on the main log page)
+        src.xmlManager.update_hat_xml(self.config.SITE.log.logDir)
 
 def date_to_datetime(date):
-    Y = int(date[:4])
-    m = int(date[4:6])
-    dd = int(date[6:8])
-    H = int(date[9:11])
-    M = int(date[11:13])
-    S = int(date[13:15])
-    return datetime.datetime(Y, m, dd, H, M, S)
\ No newline at end of file
+    '''Little method that gets year, mon, day, hour , minutes and seconds from a str in format YYYYMMDD_HHMMSS
+    
+    :param date str: The date in format YYYYMMDD_HHMMSS
+    :return: the same date and time in separate variables.
+    :rtype: (str,str,str,str,str,str)
+    '''
+    Y = date[:4]
+    m = date[4:6]
+    dd = date[6:8]
+    H = date[9:11]
+    M = date[11:13]
+    S = date[13:15]
+    return Y, m, dd, H, M, S
+
+def timedelta_total_seconds(timedelta):
+    '''Little method to replace total_seconds from datetime module in order to be compatible with old python versions
+    
+    :param timedelta datetime.timedelta: The delta between two dates
+    :return: The number of seconds corresponding to timedelta.
+    :rtype: float
+    '''
+    return (
+        timedelta.microseconds + 0.0 +
+        (timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6
\ No newline at end of file