类java.util.logging.SimpleFormatter源码实例Demo

下面列出了怎么用java.util.logging.SimpleFormatter的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: dragonwell8_jdk   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码2 项目: TencentKona-8   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码3 项目: jenkins-test-harness   文件: LoggerRule.java
/**
 * Initializes log record capture, in addition to merely printing it.
 * This allows you to call {@link #getRecords} and/or {@link #getMessages} later.
 * @param maximum the maximum number of records to keep (any further will be discarded)
 * @return this rule, for convenience
 */
public LoggerRule capture(int maximum) {
    messages = new ArrayList<>();
    ringHandler = new RingBufferLogHandler(maximum) {
        final Formatter f = new SimpleFormatter(); // placeholder instance for what should have been a static method perhaps
        @Override
        public synchronized void publish(LogRecord record) {
            super.publish(record);
            String message = f.formatMessage(record);
            Throwable x = record.getThrown();
            synchronized (messages) {
                messages.add(message == null && x != null ? x.toString() : message);
            }
        }
    };
    ringHandler.setLevel(Level.ALL);
    for (Logger logger : loggers.keySet()) {
        logger.addHandler(ringHandler);
    }
    return this;
}
 
源代码4 项目: jdk8u60   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码5 项目: launchpad-missioncontrol   文件: LoggingConfig.java
public LoggingConfig() {
    try {
        // Load a properties file from class path java.util.logging.config.file
        final LogManager logManager = LogManager.getLogManager();
        URL configURL = getClass().getResource("/logging.properties");
        if (configURL != null) {
            try (InputStream is = configURL.openStream()) {
                logManager.readConfiguration(is);
            }
        } else {
            // Programmatic configuration
            System.setProperty("java.util.logging.SimpleFormatter.format",
                               "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n");

            final ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINEST);
            consoleHandler.setFormatter(new SimpleFormatter());

            final Logger app = Logger.getLogger("app");
            app.setLevel(Level.FINEST);
            app.addHandler(consoleHandler);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
源代码6 项目: openjdk-jdk8u   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码7 项目: netbeans   文件: ExceptionTest.java
/**
 * Test PayaraException with no parameters specified throwing
 * and logging.
 */
@Test
public void testPayaraExceptionWithNothing() {
    // this message must match PayaraIdeException() constructor
    // log message.
    String gfieMsg = "Caught PayaraIdeException.";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new PayaraIdeException();
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
源代码8 项目: netbeans   文件: ExceptionTest.java
/**
 * Test PayaraException with message throwing and logging.
 */
@Test
public void testPayaraExceptionWithMsg() {
    String gfieMsg = "Test exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new PayaraIdeException(gfieMsg);
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
源代码9 项目: netbeans   文件: ExceptionTest.java
/**
 * Test GlassFishException with no parameters specified throwing
 * and logging.
 */
@Test
public void testGlassFishExceptionWithNothing() {
    // this message must match GlassFishIdeException() constructor
    // log message.
    String gfieMsg = "Caught GlassFishIdeException.";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new GlassFishIdeException();
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
源代码10 项目: netbeans   文件: ExceptionTest.java
/**
 * Test GlassFishException with message throwing and logging.
 */
@Test
public void testGlassFishExceptionWithMsg() {
    String gfieMsg = "Test exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new GlassFishIdeException(gfieMsg);
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
源代码11 项目: jdk8u_jdk   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码12 项目: vespa   文件: LogFileHandlerTestCase.java
@Test
public void testSimpleLogging() throws IOException {
    File logFile = temporaryFolder.newFile("testLogFileG1.txt");

  //create logfilehandler
  LogFileHandler h = new LogFileHandler();
  h.setFilePattern(logFile.getAbsolutePath());
  h.setFormatter(new SimpleFormatter());
  h.setRotationTimes("0 5 ...");

  //write log
  LogRecord lr = new LogRecord(Level.INFO, "testDeleteFileFirst1");
  h.publish(lr);
  h.flush();
  h.shutdown();
}
 
源代码13 项目: redpipe   文件: AppTest.java
@Test
public void testCdiInjection(TestContext context) {
  final ConsoleHandler consoleHandler = new ConsoleHandler();
  consoleHandler.setLevel(Level.FINEST);
  consoleHandler.setFormatter(new SimpleFormatter());

  final Logger app = Logger.getLogger("org.jboss.weld.vertx");
  app.setLevel(Level.FINEST);
  app.addHandler(consoleHandler);

  Async async = context.async();
    webClient.get("/test/injection")
    .as(BodyCodec.string())
    .rxSend()
    .subscribe(body -> {
        context.assertEquals(200, body.statusCode());
        async.complete();
    }, x -> { 
        x.printStackTrace();
        context.fail(x);
        async.complete();
    });
}
 
源代码14 项目: openjdk-jdk8u-backup   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
public void createLogFile()
{

    SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    String timeStamp = dateTime.format(new Date());
    StringBuilder logPath = new StringBuilder();

    logPath.append("/var/log/presto/queries-");
    logPath.append(timeStamp);
    logPath.append(".%g.log");

    try {
        logger = Logger.getLogger(loggerName);
        fh = new FileHandler(logPath.toString(), 524288000, 5, true);
        logger.addHandler(fh);
        logger.setUseParentHandlers(false);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    }
    catch (IOException e) {
        logger.info(e.getMessage());
    }
}
 
源代码16 项目: openjdk-jdk9   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码17 项目: jdk8u-jdk   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码18 项目: hottub   文件: SerializeLogRecord.java
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
源代码19 项目: gemfirexd-oss   文件: GemFireXDDataExtractorImpl.java
protected void configureLogger() throws SecurityException, IOException {
  if (logger == null) {
    logger = Logger.getLogger(LOGGER_NAME);
  }
  logger.setUseParentHandlers(false);
  logFileHandler = new FileHandler(logFilePath);
  logFileHandler.setFormatter(new SimpleFormatter());
  Level logLevel = Level.INFO;
  try {
    logLevel = Level.parse(logLevelString);
  } catch (IllegalArgumentException e) {
    logInfo("Unrecognized log level :" + logLevelString + " defaulting to :" + logLevel);
  }
  logFileHandler.setLevel(logLevel);
  logger.addHandler(logFileHandler);
}
 
源代码20 项目: xframium-java   文件: ThreadedFileHandler.java
public void configureHandler( Level baseLevel )
{
    
    
    Handler[] hList = LogManager.getLogManager().getLogger( "" ).getHandlers();
    for ( Handler h : hList )
    {
        if ( h instanceof ThreadedFileHandler )
            return;
    }
    
    setLevel( baseLevel );
    setFormatter( new SimpleFormatter() );
    
    LogManager.getLogManager().getLogger( "" ).addHandler( this );
}
 
public String getLogOutput() {
  SimpleFormatter formatter = new SimpleFormatter();
  StringBuilder sb = new StringBuilder();
  for (LogRecord loggedMessage : loggedMessages) {
    sb.append(formatter.format(loggedMessage));
  }
  return sb.toString();
}
 
@Test
public void testFlush() {
  final AtomicBoolean flushed = new AtomicBoolean(false);
  Logger.getLogger(LoggingMetricExporter.class.getName())
      .addHandler(
          new StreamHandler(System.err, new SimpleFormatter()) {
            @Override
            public synchronized void flush() {
              flushed.set(true);
            }
          });
  exporter.flush();
  assertThat(flushed.get()).isTrue();
}
 
@Test
public void testFlush() {
  final AtomicBoolean flushed = new AtomicBoolean(false);
  Logger.getLogger(LoggingSpanExporter.class.getName())
      .addHandler(
          new StreamHandler(System.err, new SimpleFormatter()) {
            @Override
            public synchronized void flush() {
              flushed.set(true);
            }
          });
  exporter.flush();
  assertThat(flushed.get()).isTrue();
}
 
源代码24 项目: android-uiconductor   文件: UicdCLI.java
private static void setRedirectOutputToFile(Path logFolder) throws IOException {
  Path logFilePath =
      Paths.get(logFolder.toString(), LOG_FILENAME_PREFIX + new Date().getTime() + ".txt");
  System.out.println("Starting print to file...\n" + logFilePath.toString());
  Handler fh = new FileHandler(logFilePath.toString());
  fh.setFormatter(new SimpleFormatter());

  // Remove the output in the console.
  LogManager.getLogManager().reset();
  Logger.getLogger("uicd").addHandler(fh);
}
 
源代码25 项目: sagacity-sqltoy   文件: LoggerUtil.java
public static Logger getLogger() {
	if (logger == null) {
		logger = Logger.getLogger("sagacity.quickvo");
		logger.setLevel(Level.ALL);
		try {
			Handler handler = new FileHandler(FileUtil.linkPath(QuickVOConstants.BASE_LOCATE, "quickvo.log"));
			handler.setFormatter(new SimpleFormatter());
			logger.addHandler(handler);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	return logger;
}
 
源代码26 项目: EnchantmentCracker   文件: Log.java
private static Logger getLogger() {
	Logger logger = Logger.getLogger("");
	logger.setUseParentHandlers(false);
	logger.addHandler(fileHandler);
	SimpleFormatter formatter = new SimpleFormatter() {
		private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		@Override
		public String format(LogRecord record) {
			String thrown;
			if (record.getThrown() == null) {
				thrown = "";
			} else {
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw);
				pw.println();
				record.getThrown().printStackTrace(pw);
				thrown = sw.toString();
			}
			return String.format("[%s] [%s/%s]: %s%s%n", dateFormat.format(record.getMillis()),
					record.getLoggerName(), record.getLevel(), record.getMessage(), thrown);
		}
	};
	for (Handler handler : logger.getHandlers()) {
		handler.setFormatter(formatter);
	}

	return logger;
}
 
源代码27 项目: protect   文件: BFTMapClientCloudFIT.java
private static void initLog() {
	try {
		boolean append = true;
		FileHandler fh = new FileHandler(BFTMapClientCloudFIT.class.getName() + ".log", append);
		fh.setFormatter(new SimpleFormatter());

		logger = Logger.getLogger(BFTMapClientCloudFIT.class.getName());
		logger.addHandler(fh);
	} catch (IOException e) {
		System.out.println("PROBLEMS]: " + e.getMessage());
		System.exit(-1);
	}
}
 
源代码28 项目: flogger   文件: GoogleLoggerTest.java
private String logRecordToString(LogRecord logRecord) {
  StringBuilder sb = new StringBuilder();
  String message = new SimpleFormatter().formatMessage(logRecord);
  sb.append(logRecord.getLevel()).append(": ").append(message).append("\n");

  Throwable thrown = logRecord.getThrown();
  if (thrown != null) {
    sb.append(thrown);
  }
  return sb.toString().trim();
}
 
源代码29 项目: RepoSense   文件: LogsManager.java
/**
 * Creates a {@code FileHandler} for the log file.
 *
 * @throws IOException if there are problems opening the file.
 */
private static FileHandler createFileHandler() throws IOException {
    Path path = logFolderLocation.resolve(LOG_FOLDER_NAME).resolve(LOG_FILE_NAME);
    FileHandler fileHandler = new FileHandler(path.toString(), MAX_FILE_SIZE_IN_BYTES, FILE_COUNT, true);
    fileHandler.setFormatter(new SimpleFormatter());
    fileHandler.setLevel(currentFileLogLevel);
    return fileHandler;
}
 
源代码30 项目: netbeans   文件: ExceptionTest.java
/**
 * Test PayaraException with message and cause <code>Throwable</code>
 * throwing and logging.
 */
@Test
public void testPayaraExceptionWithMsgAndCause() {
    String gfieMsg = "Test exception";
    String causeMsg = "Cause exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        try {
            throw new Exception(causeMsg);
        } catch (Exception e) {
            throw new PayaraIdeException(gfieMsg, e);
        }
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int containsGfieMsg = logMsg.indexOf(gfieMsg);
    int containsCauseMsg = logMsg.indexOf(causeMsg);
    assertTrue(containsGfieMsg > -1 && containsCauseMsg > -1);
}
 
 类所在包
 类方法
 同包方法