# # The Logging Module # import os,sys,time # # Module globals # This are changed by the indicated accessor functions. # gUseLogFile = 1 # Set by 'ToFile()' and ToScreen()' gUseScreen = 0 # Set by 'ToFile()' and ToScreen()' gLogFileName = 'logging.txt' # Set by 'ToFile()'. gAutoNewLine = 0 # See 'AutoNewLine()' gTimeStampNextWrite = 0 gTimeStampTime = time.time() # # The functions below are not for external consumption. They implement # def WriteRaw(msg): if gUseScreen: sys.stdout.write(msg) if gUseLogFile: # timestamp calculations need to be made for every write to allow server processes # which may run for months on end fn = gLogFileName # Append month to end of file name. t = time.localtime() fn = fn + ' ' + str(t[1]) + '-' + str(t[0]) fn = fn + '.txt' # removing the text flag as it is not cross platform #f = os.open(fn, os.O_CREAT | os.O_APPEND | os.O_TEXT | os.O_WRONLY) f = os.open(fn, os.O_CREAT | os.O_APPEND | os.O_WRONLY) os.fdopen(f, 'w').write(msg) # # The following functions make up the interface to this module. # def ToFile(fn, alsoToScreen = 0): ''' Start sending log messages to the text file indicated by 'fn'. 'fn' should not end with any extension. The month and ".txt" will be appended to whatever file name you pass. ''' global gUseScreen, gUseLogFile, gLogFileName # Remove extension if present. Save the root file name in a global to be used by WriteRaw if fn[-4:] == '.txt' or fn[-4:] == '.TXT': fn = fn[:-4] gUseScreen = alsoToScreen gUseLogFile = 1 gLogFileName = fn def ToScreen(): ''' Start sending log messages to the screen. ''' global gUseScreen, gUseLogFile gUseScreen = 1 gUseLogFile = 0 def ToFileAndScreen(fn): ToFile(fn, 1) def AutoNewLine(b): ''' Set whether or not a new line character should automatically be appending to the end of all calls to 'Write()'. Pass '1' to append the new line, '0' to not. ''' global gAutoNewLine gAutoNewLine = b def TimeStamp(): ''' Write a time stamp to the current logging device. ''' WriteRaw('--------------------------------------------------------------------\n') if gTimeStampNextWrite: WriteRaw(time.ctime(gTimeStampTime) + '\n') else: WriteRaw(time.ctime() + '\n') WriteRaw('\n') def TimeStampNextWrite(): global gTimeStampNextWrite, gTimeStampTime gTimeStampNextWrite = 1 gTimeStampTime = time.time() def CancelTimeStamp(): global gTimeStampNextWrite gTimeStampNextWrite = 0 def Write(msg): ''' Write a log message to the output device. ''' global gTimeStampNextWrite if gTimeStampNextWrite: TimeStamp() gTimeStampNextWrite = 0 if gAutoNewLine: WriteRaw(msg + '\n') else: WriteRaw(msg)