def file_logger(self, append, logFolder, name, messageLevel): super(messageLevel) if (logFolder == None or logFolder == ""): directory = DEFAULTLOGFOLDER else: directory = logFolder if not os.path.exists(directory): pathlib.Path(directory).mkdir(parents=True, exist_ok=True) newName = make_valid_file_name(name) # if (!name.toLowerCase().endsWith(this.getExtension())): if (not name.lower().endswith(get_extension())): name += get_extension() fileName = name filePath = Path.get(directory, name).normalize().toString() messageType = messageLevel if (path.exists(filePath) and not append): try: writer = [filePath, False] writer.write("") writer.flush() except Exception as e: # Failed to write to the event log, write error to the console instead console = ConsoleLogger() console.log_message( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to write to event log because: " + e.args))
def make_valid_file_name(name): if name == None or name == "": raise FormatError("Blank or null file name was provided") # Replace invalid characters replacedName = name try: replacedName = name.replaceAll("[^a-zA-Z0-9\\._\\- ]+", "~") except Error as e: console = ConsoleLogger() console.logMessage( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to Replace Invalid Characters because: " + e.args)) return replacedName
def get_logger(self, fileName): # Disable logging means we just send any logged messages to the console if (get_logging_enabled_setting() == LoggingEnabled.NO): return ConsoleLogger() logDirectory = get_log_directory() loggingLevel = get_logging_level_setting() logType = Config.getGeneralValue("LogType", "CONSOLE").toUpperCase() if logType == "CONSOLE": return ConsoleLogger(loggingLevel) elif logType == "TXT": return FileLogger(False, logDirectory, fileName, loggingLevel) else: raise ValueError( StringProcessor.safeFormatter( "Log type %s is not a valid option", Config.get_general_value("LogType", "CONSOLE")))
def create_Logger(self): loggingEnabledSetting = LoggingConfig.get_LoggingEnabled_Setting(); self.set_Logged_Exceptions([]) if (loggingEnabledSetting != LoggingEnabled.NO): return LoggingConfig.getLogger(StringProcessor .safeFormatter("%s - %s", fullyQualifiedTestClassName.get(), datetime.utcnow().strftime("uuuu-MM-dd-HH-mm-ss-SSSS"))) else: return ConsoleLogger()
def log_message(self, messageType, message, args): # If the message level is greater that the current log level then do not log it. if (Logger.should_message_be_logged(messageType)): # Log the message # lock (this.FileLock): date = datetime.now().strftime(Logger.DEFAULTDATEFORMAT) #date = dateTime.now().UtcNow()ToString(Logger.DEFAULTDATEFORMAT, CultureInfo.InvariantCulture); writer = [] try: #using (StreamWriter writer = new StreamWriter(this.FilePath, true)): # Set the style writer.append(get_text_with_color_flag(messageType)) # Add the content writer.WriteLine( StringProcessor.SafeFormatter("{0}{1}", os.linesep, date)) writer.Write( StringProcessor.SafeFormatter("{0}:\t", messageType.ToString())) writer.WriteLine(StringProcessor.SafeFormatter(message, args)) # Close off the style writer.Write("</p>") # Close the pre tag when logging Errors if (messageType == "ERROR"): writer.Write("</pre>") except Exception as e: # Failed to write to the event log, write error to the console instead console = ConsoleLogger() console.LogMessage( MessageType.ERROR, StringProcessor.SafeFormatter( "Failed to write to event log because: {0}", e.message)) console.LogMessage(messageType, message, args)
def tear_down(self): try: self.before_logging_teardown(testResult); except Exception as e: self.try_to_log(MessageType.WARNING, "Failed before logging teardown because: %s", e.getMessage()) # Log the test result if testResult.getStatus() == "SUCCESS": tryToLog(MessageType.SUCCESS, "Test Passed") elif testResult.getStatus() == "FAILURE": tryToLog(MessageType.ERROR, "Test Failed") elif testResult.getStatus() == "SKIP": tryToLog(MessageType.INFORMATION, "Test was skipped"); else: tryToLog(MessageType.WARNING, "Test had an unexpected result.") # Cleanup log files we don't want try: if self.Log is FileLogger and testResult == TestResultType.PASS and self.LoggingEnabledSetting == LoggingEnabled.ONFAIL: os.remove(FileLogger.Log.getFilePath) except Exception as e: tryToLog(MessageType.WARNING, "Failed to cleanup log files because: %s", e.getMessage()) # Get the Fully Qualified Test Name fullyQualifiedTestName = fullyQualifiedTestClassName try: baseTestObject = get_test_object() # Release logged messages loggedExceptions.remove(fullyQualifiedTestName) # Release the Base Test Object baseTestObjects.remove(fullyQualifiedTestName, baseTestObject) # Create console logger to log subsequent messages self.set_test_object(BaseTestObject(ConsoleLogger(), fullyQualifiedTestName)) fullyQualifiedTestClassName.remove()
def log_message(self, messageType, message, args): # If the message level is greater that the current log level then do not log it. if (self.should_message_be_logged(messageType)): try: ''' (FileWriter fw = new FileWriter(this.filePath, true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter writer = new PrintWriter(bw)) writer.println( StringProcessor.safeFormatter("%s%s", Config.NEW_LINE, System.currentTimeMillis())); writer.print(StringProcessor.safeFormatter("%s:\t", messageType.toString())); writer.println(StringProcessor.safeFormatter(message, args)); writer.flush(); ''' except Error as e: # Failed to write to the event log, write error to the console instead console = ConsoleLogger() console.logMessage( MessageType.ERROR, StringProcessor.safeFormatter( "Failed to write to event log because: " + e.args)) console.logMessage(messageType, message, args)
def consoleLoggerLogMessage(self): console = ConsoleLogger() console.logMessage("Test String %s %s", "args1", "args2")
def consoleLoggerWriteMessageLineSelectType(self): console = ConsoleLogger() console.write(MessageType.GENERIC, "TestString %s", "args1")
def consoleLoggerWriteLineMessage(self): console = ConsoleLogger() console.write("Test String %s %s", "args1", "args2")
def consoleLoggerLogMessageSelectType(self): console = ConsoleLogger() console.logMessage(MessageType.GENERIC, "Test String %s", "args1")
def __init__(self): self.Log = ConsoleLogger()