15b6bfdb9SJed Brownfrom __future__ import absolute_import 2179860b2SJed Brownimport args 3179860b2SJed Brownimport sys 4179860b2SJed Brownimport os 59561296dSJacob Faibussowitschimport textwrap 6179860b2SJed Brown 7179860b2SJed Brown# Ugly stuff to have curses called ONLY once, instead of for each 8179860b2SJed Brown# new Configure object created (and flashing the screen) 9179860b2SJed Brownglobal LineWidth 10179860b2SJed Brownglobal RemoveDirectory 11179860b2SJed Brownglobal backupRemoveDirectory 12179860b2SJed BrownLineWidth = -1 13179860b2SJed BrownRemoveDirectory = os.path.join(os.getcwd(),'') 14179860b2SJed BrownbackupRemoveDirectory = '' 15179860b2SJed Brown 16179860b2SJed Brownclass Logger(args.ArgumentProcessor): 17179860b2SJed Brown '''This class creates a shared log and provides methods for writing to it''' 18179860b2SJed Brown defaultLog = None 19179860b2SJed Brown defaultOut = sys.stdout 20179860b2SJed Brown 21179860b2SJed Brown def __init__(self, clArgs = None, argDB = None, log = None, out = defaultOut, debugLevel = None, debugSections = None, debugIndent = None): 22179860b2SJed Brown args.ArgumentProcessor.__init__(self, clArgs, argDB) 23179860b2SJed Brown self.logName = None 24179860b2SJed Brown self.log = log 25179860b2SJed Brown self.out = out 26179860b2SJed Brown self.debugLevel = debugLevel 27179860b2SJed Brown self.debugSections = debugSections 28179860b2SJed Brown self.debugIndent = debugIndent 299561296dSJacob Faibussowitsch self.dividerLength = 93 30179860b2SJed Brown self.getRoot() 31179860b2SJed Brown return 32179860b2SJed Brown 33179860b2SJed Brown def __getstate__(self): 34179860b2SJed Brown '''We do not want to pickle the default log stream''' 35179860b2SJed Brown d = args.ArgumentProcessor.__getstate__(self) 36b59d1e59SMatthew G. Knepley if 'logBkp' in d: 37b59d1e59SMatthew G. Knepley del d['logBkp'] 38179860b2SJed Brown if 'log' in d: 39179860b2SJed Brown if d['log'] is Logger.defaultLog: 40179860b2SJed Brown del d['log'] 41179860b2SJed Brown else: 42179860b2SJed Brown d['log'] = None 43179860b2SJed Brown if 'out' in d: 44179860b2SJed Brown if d['out'] is Logger.defaultOut: 45179860b2SJed Brown del d['out'] 46179860b2SJed Brown else: 47179860b2SJed Brown d['out'] = None 48179860b2SJed Brown return d 49179860b2SJed Brown 50179860b2SJed Brown def __setstate__(self, d): 51179860b2SJed Brown '''We must create the default log stream''' 52179860b2SJed Brown args.ArgumentProcessor.__setstate__(self, d) 53179860b2SJed Brown if not 'log' in d: 54179860b2SJed Brown self.log = self.createLog(None) 55179860b2SJed Brown if not 'out' in d: 56179860b2SJed Brown self.out = Logger.defaultOut 57179860b2SJed Brown self.__dict__.update(d) 58179860b2SJed Brown return 59179860b2SJed Brown 60179860b2SJed Brown def setupArguments(self, argDB): 61179860b2SJed Brown '''Setup types in the argument database''' 62179860b2SJed Brown import nargs 63179860b2SJed Brown 64179860b2SJed Brown argDB = args.ArgumentProcessor.setupArguments(self, argDB) 6503e6d329SSatish Balay argDB.setType('log', nargs.Arg(None, 'buildsystem.log', 'The filename for the log')) 66179860b2SJed Brown argDB.setType('logAppend', nargs.ArgBool(None, 0, 'The flag determining whether we backup or append to the current log', isTemporary = 1)) 67179860b2SJed Brown argDB.setType('debugLevel', nargs.ArgInt(None, 3, 'Integer 0 to 4, where a higher level means more detail', 0, 5)) 68179860b2SJed Brown argDB.setType('debugSections', nargs.Arg(None, [], 'Message types to print, e.g. [compile,link,hg,install]')) 69179860b2SJed Brown argDB.setType('debugIndent', nargs.Arg(None, ' ', 'The string used for log indentation')) 70179860b2SJed Brown argDB.setType('scrollOutput', nargs.ArgBool(None, 0, 'Flag to allow output to scroll rather than overwriting a single line')) 71179860b2SJed Brown argDB.setType('noOutput', nargs.ArgBool(None, 0, 'Flag to suppress output to the terminal')) 72179860b2SJed Brown return argDB 73179860b2SJed Brown 74179860b2SJed Brown def setup(self): 75179860b2SJed Brown '''Setup the terminal output and filtering flags''' 76179860b2SJed Brown self.log = self.createLog(self.logName, self.log) 77179860b2SJed Brown args.ArgumentProcessor.setup(self) 78179860b2SJed Brown 79179860b2SJed Brown if self.argDB['noOutput']: 80179860b2SJed Brown self.out = None 81179860b2SJed Brown if self.debugLevel is None: 82179860b2SJed Brown self.debugLevel = self.argDB['debugLevel'] 83179860b2SJed Brown if self.debugSections is None: 84179860b2SJed Brown self.debugSections = self.argDB['debugSections'] 85179860b2SJed Brown if self.debugIndent is None: 86179860b2SJed Brown self.debugIndent = self.argDB['debugIndent'] 87179860b2SJed Brown return 88179860b2SJed Brown 89179860b2SJed Brown def checkLog(self, logName): 90179860b2SJed Brown import nargs 91179860b2SJed Brown import os 92179860b2SJed Brown 93179860b2SJed Brown if logName is None: 94179860b2SJed Brown logName = nargs.Arg.findArgument('log', self.clArgs) 95179860b2SJed Brown if logName is None: 96179860b2SJed Brown if not self.argDB is None and 'log' in self.argDB: 97179860b2SJed Brown logName = self.argDB['log'] 98179860b2SJed Brown else: 99179860b2SJed Brown logName = 'default.log' 100179860b2SJed Brown self.logName = logName 101179860b2SJed Brown self.logExists = os.path.exists(self.logName) 102179860b2SJed Brown return self.logExists 103179860b2SJed Brown 104179860b2SJed Brown def createLog(self, logName, initLog = None): 105179860b2SJed Brown '''Create a default log stream, unless initLog is given''' 106179860b2SJed Brown import nargs 107179860b2SJed Brown 108179860b2SJed Brown if not initLog is None: 109179860b2SJed Brown log = initLog 110179860b2SJed Brown else: 111179860b2SJed Brown if Logger.defaultLog is None: 112179860b2SJed Brown appendArg = nargs.Arg.findArgument('logAppend', self.clArgs) 113179860b2SJed Brown if self.checkLog(logName): 114179860b2SJed Brown if not self.argDB is None and ('logAppend' in self.argDB and self.argDB['logAppend']) or (not appendArg is None and bool(appendArg)): 115c6ef1b5bSJed Brown Logger.defaultLog = open(self.logName, 'a') 116179860b2SJed Brown else: 117179860b2SJed Brown try: 118179860b2SJed Brown import os 119179860b2SJed Brown 120179860b2SJed Brown os.rename(self.logName, self.logName+'.bkp') 121c6ef1b5bSJed Brown Logger.defaultLog = open(self.logName, 'w') 122179860b2SJed Brown except OSError: 12315ac2963SJed Brown sys.stdout.write('WARNING: Cannot backup log file, appending instead.\n') 124c6ef1b5bSJed Brown Logger.defaultLog = open(self.logName, 'a') 125179860b2SJed Brown else: 126c6ef1b5bSJed Brown Logger.defaultLog = open(self.logName, 'w') 127179860b2SJed Brown log = Logger.defaultLog 128179860b2SJed Brown return log 129179860b2SJed Brown 130179860b2SJed Brown def closeLog(self): 131179860b2SJed Brown '''Closes the log file''' 132179860b2SJed Brown self.log.close() 133179860b2SJed Brown 134a75b4e77SMatthew G. Knepley def saveLog(self): 135dc0f114dSBarry Smith if self.debugLevel <= 3: return 1362d964b9fSJed Brown import io 137a75b4e77SMatthew G. Knepley self.logBkp = self.log 1382d964b9fSJed Brown self.log = io.StringIO() 139a75b4e77SMatthew G. Knepley 140a75b4e77SMatthew G. Knepley def restoreLog(self): 141dc0f114dSBarry Smith if self.debugLevel <= 3: return 142a75b4e77SMatthew G. Knepley s = self.log.getvalue() 143a75b4e77SMatthew G. Knepley self.log.close() 144a75b4e77SMatthew G. Knepley self.log = self.logBkp 145a75b4e77SMatthew G. Knepley del(self.logBkp) 146a75b4e77SMatthew G. Knepley return s 147a75b4e77SMatthew G. Knepley 148179860b2SJed Brown def getLinewidth(self): 149179860b2SJed Brown global LineWidth 150179860b2SJed Brown if not hasattr(self, '_linewidth'): 151179860b2SJed Brown if self.out is None or not self.out.isatty() or self.argDB['scrollOutput']: 152179860b2SJed Brown self._linewidth = -1 153179860b2SJed Brown else: 154179860b2SJed Brown if LineWidth == -1: 155179860b2SJed Brown try: 156179860b2SJed Brown import curses 157179860b2SJed Brown 158179860b2SJed Brown try: 159179860b2SJed Brown curses.setupterm() 160179860b2SJed Brown (y, self._linewidth) = curses.initscr().getmaxyx() 161179860b2SJed Brown curses.endwin() 162179860b2SJed Brown except curses.error: 163179860b2SJed Brown self._linewidth = -1 164179860b2SJed Brown except: 165179860b2SJed Brown self._linewidth = -1 166179860b2SJed Brown LineWidth = self._linewidth 167179860b2SJed Brown else: 168179860b2SJed Brown self._linewidth = LineWidth 169179860b2SJed Brown return self._linewidth 170179860b2SJed Brown def setLinewidth(self, linewidth): 171179860b2SJed Brown self._linewidth = linewidth 172179860b2SJed Brown return 173179860b2SJed Brown linewidth = property(getLinewidth, setLinewidth, doc = 'The maximum number of characters per log line') 174179860b2SJed Brown 175179860b2SJed Brown def checkWrite(self, f, debugLevel, debugSection, writeAll = 0): 176179860b2SJed Brown '''Check whether the log line should be written 177179860b2SJed Brown - If writeAll is true, return true 178179860b2SJed Brown - If debugLevel >= current level, and debugSection in current section or sections is empty, return true''' 179179860b2SJed Brown if not isinstance(debugLevel, int): 180179860b2SJed Brown raise RuntimeError('Debug level must be an integer: '+str(debugLevel)) 181179860b2SJed Brown if f is None: 182179860b2SJed Brown return False 183179860b2SJed Brown if writeAll: 184179860b2SJed Brown return True 185179860b2SJed Brown if self.debugLevel >= debugLevel and (not len(self.debugSections) or debugSection in self.debugSections): 186179860b2SJed Brown return True 187179860b2SJed Brown return False 188179860b2SJed Brown 189179860b2SJed Brown def logIndent(self, debugLevel = -1, debugSection = None, comm = None): 190179860b2SJed Brown '''Write the proper indentation to the log streams''' 191179860b2SJed Brown import traceback 192179860b2SJed Brown 193179860b2SJed Brown indentLevel = len(traceback.extract_stack())-5 194179860b2SJed Brown for writeAll, f in enumerate([self.out, self.log]): 195179860b2SJed Brown if self.checkWrite(f, debugLevel, debugSection, writeAll): 196179860b2SJed Brown if not comm is None: 197179860b2SJed Brown f.write('[') 198179860b2SJed Brown f.write(str(comm.rank())) 199179860b2SJed Brown f.write(']') 200179860b2SJed Brown for i in range(indentLevel): 201179860b2SJed Brown f.write(self.debugIndent) 202179860b2SJed Brown return 203179860b2SJed Brown 204179860b2SJed Brown def logBack(self): 205179860b2SJed Brown '''Backup the current line if we are not scrolling output''' 206*d1b3ee28SJacob Faibussowitsch if self.out is not None and self.linewidth > 0: 207179860b2SJed Brown self.out.write('\r') 208179860b2SJed Brown return 209179860b2SJed Brown 210179860b2SJed Brown def logClear(self): 211179860b2SJed Brown '''Clear the current line if we are not scrolling output''' 212*d1b3ee28SJacob Faibussowitsch if self.out is not None and self.linewidth > 0: 213*d1b3ee28SJacob Faibussowitsch self.out.write((' '*self.linewidth).join(('\r','\r'))) 214179860b2SJed Brown return 215179860b2SJed Brown 216*d1b3ee28SJacob Faibussowitsch def logPrintDivider(self, single = False, **kwargs): 217*d1b3ee28SJacob Faibussowitsch divider = ('-' if single else '=')*self.dividerLength 218*d1b3ee28SJacob Faibussowitsch return self.logPrint(divider, **kwargs) 219179860b2SJed Brown 220*d1b3ee28SJacob Faibussowitsch def logPrintWarning(self, msg, title = None, **kwargs): 221*d1b3ee28SJacob Faibussowitsch if title is None: 222*d1b3ee28SJacob Faibussowitsch title = 'WARNING' 223*d1b3ee28SJacob Faibussowitsch return self.logPrintBox(msg,title='***** {} *****'.format(title),**kwargs) 224*d1b3ee28SJacob Faibussowitsch 225*d1b3ee28SJacob Faibussowitsch def logPrintBox(self, msg, debugLevel = -1, debugSection = 'screen', indent = 1, comm = None, rmDir = 1, prefix = None, title = None): 2261edc1b4bSJacob Faibussowitsch def center_wrap(banner,text,**kwargs): 2271edc1b4bSJacob Faibussowitsch def center_line(line): 2281edc1b4bSJacob Faibussowitsch return line.center(self.dividerLength).rstrip() 2291edc1b4bSJacob Faibussowitsch 2301edc1b4bSJacob Faibussowitsch wrapped = textwrap.wrap(textwrap.dedent(text),**kwargs) 2311edc1b4bSJacob Faibussowitsch if len(wrapped) == 1: 232*d1b3ee28SJacob Faibussowitsch # center-justify single lines, and remove the bogus prefix 233*d1b3ee28SJacob Faibussowitsch wrapped[0] = center_line(wrapped[0].lstrip()) 2341edc1b4bSJacob Faibussowitsch if banner: 2351edc1b4bSJacob Faibussowitsch # add the banner 2361edc1b4bSJacob Faibussowitsch wrapped.insert(0,center_line(banner)) 2371edc1b4bSJacob Faibussowitsch return '\n'.join(wrapped) 2381edc1b4bSJacob Faibussowitsch 2391edc1b4bSJacob Faibussowitsch 2409561296dSJacob Faibussowitsch if prefix is None: 2419561296dSJacob Faibussowitsch prefix = ' '*2 2429561296dSJacob Faibussowitsch 243*d1b3ee28SJacob Faibussowitsch if rmDir: 244*d1b3ee28SJacob Faibussowitsch rmDir = center_wrap(title,self.logStripDirectory(msg),width=self.dividerLength-2,initial_indent=prefix,subsequent_indent=prefix) 245*d1b3ee28SJacob Faibussowitsch msg = center_wrap(title,msg,width=self.dividerLength-2,initial_indent=prefix,subsequent_indent=prefix) 246179860b2SJed Brown self.logClear() 247*d1b3ee28SJacob Faibussowitsch self.logPrintDivider(debugLevel = debugLevel, debugSection = debugSection, forceNewLine = True) 248*d1b3ee28SJacob Faibussowitsch self.logPrint(msg, debugLevel = debugLevel, debugSection = debugSection, rmDir = rmDir, indent = indent, comm = comm, forceNewLine = True) 249*d1b3ee28SJacob Faibussowitsch self.logPrintDivider(debugLevel = debugLevel, debugSection = debugSection, forceNewLine = True) 250179860b2SJed Brown self.logPrint('', debugLevel = debugLevel, debugSection = debugSection) 251179860b2SJed Brown return 252179860b2SJed Brown 253*d1b3ee28SJacob Faibussowitsch def logStripDirectory(self,msg): 254*d1b3ee28SJacob Faibussowitsch return msg.replace(RemoveDirectory,'') 255*d1b3ee28SJacob Faibussowitsch 256179860b2SJed Brown def logClearRemoveDirectory(self): 257179860b2SJed Brown global RemoveDirectory 258179860b2SJed Brown global backupRemoveDirectory 259179860b2SJed Brown backupRemoveDirectory = RemoveDirectory 260179860b2SJed Brown RemoveDirectory = '' 261179860b2SJed Brown 262179860b2SJed Brown def logResetRemoveDirectory(self): 263179860b2SJed Brown global RemoveDirectory 264179860b2SJed Brown global backupRemoveDirectory 265179860b2SJed Brown RemoveDirectory = backupRemoveDirectory 266179860b2SJed Brown 267179860b2SJed Brown 268d15db81bSBarry Smith def logWrite(self, msg, debugLevel = -1, debugSection = None, forceScroll = 0, rmDir = 1): 269179860b2SJed Brown '''Write the message to the log streams''' 270b5f71184SBarry Smith '''Generally goes to the file but not the screen''' 271dc0f114dSBarry Smith if not msg: return 272179860b2SJed Brown for writeAll, f in enumerate([self.out, self.log]): 273179860b2SJed Brown if self.checkWrite(f, debugLevel, debugSection, writeAll): 274179860b2SJed Brown if not forceScroll and not writeAll and self.linewidth > 0: 275*d1b3ee28SJacob Faibussowitsch self.logClear() 276*d1b3ee28SJacob Faibussowitsch if rmDir: 277*d1b3ee28SJacob Faibussowitsch if isinstance(rmDir,str): 278*d1b3ee28SJacob Faibussowitsch msg = rmDir 279*d1b3ee28SJacob Faibussowitsch else: 280*d1b3ee28SJacob Faibussowitsch msg = self.logStripDirectory(msg) 281*d1b3ee28SJacob Faibussowitsch for ms in msg.splitlines(): 282*d1b3ee28SJacob Faibussowitsch f.write(ms[:self.linewidth]) 283179860b2SJed Brown else: 284179860b2SJed Brown if not debugSection is None and not debugSection == 'screen' and len(msg): 285179860b2SJed Brown f.write(str(debugSection)) 286179860b2SJed Brown f.write(': ') 287179860b2SJed Brown f.write(msg) 288179860b2SJed Brown if hasattr(f, 'flush'): 289179860b2SJed Brown f.flush() 290179860b2SJed Brown return 291179860b2SJed Brown 292*d1b3ee28SJacob Faibussowitsch def logPrint(self, msg, debugLevel = -1, debugSection = None, indent = 1, comm = None, forceScroll = 0, rmDir = 1, forceNewLine = False): 293179860b2SJed Brown '''Write the message to the log streams with proper indentation and a newline''' 294b5f71184SBarry Smith '''Generally goes to the file and the screen''' 295179860b2SJed Brown if indent: 296179860b2SJed Brown self.logIndent(debugLevel, debugSection, comm) 297d15db81bSBarry Smith self.logWrite(msg, debugLevel, debugSection, forceScroll = forceScroll, rmDir = rmDir) 298179860b2SJed Brown for writeAll, f in enumerate([self.out, self.log]): 299179860b2SJed Brown if self.checkWrite(f, debugLevel, debugSection, writeAll): 300*d1b3ee28SJacob Faibussowitsch if forceNewLine or writeAll or self.linewidth < 0: 301179860b2SJed Brown f.write('\n') 302179860b2SJed Brown return 303179860b2SJed Brown 304179860b2SJed Brown 305179860b2SJed Brown def getRoot(self): 306179860b2SJed Brown '''Return the directory containing this module 307179860b2SJed Brown - This has the problem that when we reload a module of the same name, this gets screwed up 308179860b2SJed Brown Therefore, we call it in the initializer, and stash it''' 309179860b2SJed Brown #print ' In getRoot' 310179860b2SJed Brown #print hasattr(self, '__root') 311179860b2SJed Brown #print ' done checking' 312179860b2SJed Brown if not hasattr(self, '__root'): 313179860b2SJed Brown import os 314179860b2SJed Brown import sys 315179860b2SJed Brown 316179860b2SJed Brown # Work around a bug with pdb in 2.3 317179860b2SJed Brown if hasattr(sys.modules[self.__module__], '__file__') and not os.path.basename(sys.modules[self.__module__].__file__) == 'pdb.py': 318179860b2SJed Brown self.__root = os.path.abspath(os.path.dirname(sys.modules[self.__module__].__file__)) 319179860b2SJed Brown else: 320179860b2SJed Brown self.__root = os.getcwd() 321179860b2SJed Brown #print ' Exiting getRoot' 322179860b2SJed Brown return self.__root 323179860b2SJed Brown def setRoot(self, root): 324179860b2SJed Brown self.__root = root 325179860b2SJed Brown return 326179860b2SJed Brown root = property(getRoot, setRoot, doc = 'The directory containing this module') 327