下面列出了怎么用java.util.logging.SimpleFormatter的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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;
}
/**
* 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 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();
}
}
/**
* 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);
}
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
}
@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();
}
@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();
});
}
/**
* 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());
}
}
/**
* 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);
}
}
/**
* 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);
}
}
/**
* 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);
}
}
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);
}
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();
}
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);
}
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;
}
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;
}
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);
}
}
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();
}
/**
* 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;
}
/**
* 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);
}