下面列出了怎么用java.util.logging.Formatter的API类实例代码及写法,或者点击链接到github查看源代码。
static void setupLogging() {
final long start = currentTimeMillis();
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
handler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return String.format("%7d - %s%n", record.getMillis() - start, record.getMessage());
}
});
Logger[] loggers = {
Logger.getLogger(DenominatorD.class.getPackage().getName()),
Logger.getLogger(feign.Logger.class.getName()),
Logger.getLogger(MockWebServer.class.getName())
};
for (Logger logger : loggers) {
logger.setLevel(Level.FINE);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
}
}
/**
* Sets the attachment <code>Formatter</code> object for this handler.
* The number of formatters determines the number of attachments per
* email. This method should be the first attachment method called.
* To remove all attachments, call this method with empty array.
* @param formatters a non null array of formatters.
* @throws SecurityException if a security manager exists and the
* caller does not have <code>LoggingPermission("control")</code>.
* @throws NullPointerException if the given array or any array index is
* <code>null</code>.
* @throws IllegalStateException if called from inside a push.
*/
public final void setAttachmentFormatters(Formatter... formatters) {
checkAccess();
if (formatters.length == 0) { //Null check and length check.
formatters = emptyFormatterArray();
} else {
formatters = Arrays.copyOf(formatters,
formatters.length, Formatter[].class);
for (int i = 0; i < formatters.length; ++i) {
if (formatters[i] == null) {
throw new NullPointerException(atIndexMsg(i));
}
}
}
synchronized (this) {
if (isWriting) {
throw new IllegalStateException();
}
this.attachmentFormatters = formatters;
this.alignAttachmentFilters();
this.alignAttachmentNames();
}
}
/** Set up console handler */
public static Handler setUpConsoleHandler() {
final ConsoleHandler handler = new ConsoleHandler() {
@Override
protected void setOutputStream(final OutputStream out) throws SecurityException {
super.setOutputStream(System.out);
}
};
handler.setLevel(Level.ALL);
final Formatter formatter = new Formatter() {
@Override
public String format(final LogRecord record) {
return record.getMessage();
}
};
handler.setFormatter(formatter);
return handler;
}
/**
* Gets and creates the formatter from the LogManager or creates the default
* formatter.
*
* @param p the class name prefix.
* @return the formatter.
* @throws NullPointerException if the given argument is null.
* @throws UndeclaredThrowableException if the formatter can not be created.
*/
private Formatter initFormatter(final String p) {
Formatter f;
String v = fromLogManager(p.concat(".formatter"));
if (v != null && v.length() != 0) {
if (!"null".equalsIgnoreCase(v)) {
try {
f = LogManagerProperties.newFormatter(v);
} catch (final RuntimeException re) {
throw re;
} catch (final Exception e) {
throw new UndeclaredThrowableException(e);
}
} else {
f = null;
}
} else {
//Don't force the byte code verifier to load the formatter.
f = Formatter.class.cast(new CompactFormatter());
}
return f;
}
public static void initDebugLog(FMLPreInitializationEvent event) throws IOException {
if (DebugLog.init)
return;
DebugLog.fh = new FileHandler(new File(new File(event.getModConfigurationDirectory().getParentFile(),"logs"),"BWLog.log").toString());
DebugLog.utilLog = Logger.getLogger("DebugLog");
DebugLog.utilLog.setUseParentHandlers(false);
DebugLog.utilLog.addHandler(DebugLog.fh);
Formatter formatter = new Formatter() {
@Override
public String format(LogRecord record) {
SimpleDateFormat logTime = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(record.getMillis());
return "Level: " + record.getLevel()
+" at " + logTime.format(cal.getTime())
+ " " + record.getMessage() + "\n";
}
};
DebugLog.fh.setFormatter(formatter);
DebugLog.init = true;
}
public static JsonFormatter getJsonFormatter() {
LogManager logManager = LogManager.getLogManager();
assertThat(logManager).isInstanceOf(org.jboss.logmanager.LogManager.class);
DelayedHandler delayedHandler = InitialConfigurator.DELAYED_HANDLER;
assertThat(Logger.getLogger("").getHandlers()).contains(delayedHandler);
assertThat(delayedHandler.getLevel()).isEqualTo(Level.ALL);
Handler handler = Arrays.stream(delayedHandler.getHandlers())
.filter(h -> (h instanceof ConsoleHandler))
.findFirst().orElse(null);
assertThat(handler).isNotNull();
assertThat(handler.getLevel()).isEqualTo(Level.WARNING);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(JsonFormatter.class);
return (JsonFormatter) formatter;
}
public RuntimeValue<Optional<Formatter>> initializeJsonLogging(final JsonConfig config) {
if (!config.enable) {
return new RuntimeValue<>(Optional.empty());
}
final JsonFormatter formatter = new JsonFormatter();
formatter.setPrettyPrint(config.prettyPrint);
final String dateFormat = config.dateFormat;
if (!dateFormat.equals("default")) {
formatter.setDateFormat(dateFormat);
}
formatter.setExceptionOutputType(config.exceptionOutputType);
formatter.setPrintDetails(config.printDetails);
config.recordDelimiter.ifPresent(formatter::setRecordDelimiter);
final String zoneId = config.zoneId;
if (!zoneId.equals("default")) {
formatter.setZoneId(zoneId);
}
return new RuntimeValue<>(Optional.of(formatter));
}
/**
* Visible version of {@link java.util.logging.LogManager#getFormatterProperty(String, java.util.logging.Formatter)} .
*
* We return an instance of the class named by the "name" property.
*
* If the property is not defined or has problems we return the defaultValue.
*/
public static Formatter getFormatterProperty(@Nonnull LogManager manager, @Nullable String name, @Nullable Formatter defaultValue) {
if (name == null) {
return defaultValue;
}
String val = manager.getProperty(name);
try {
if (val != null) {
Class clz = ClassLoader.getSystemClassLoader().loadClass(val);
return (Formatter) clz.newInstance();
}
} catch (Exception ex) {
// We got one of a variety of exceptions in creating the
// class or creating an instance.
// Drop through.
}
// We got an exception. Return the defaultValue.
return defaultValue;
}
public void testOwnFormatter() throws UnsupportedEncodingException {
class MyFrmtr extends Formatter {
private int cnt;
@Override
public String format(LogRecord record) {
cnt++;
return record.getMessage();
}
}
MyFrmtr my = new MyFrmtr();
ByteArrayOutputStream os = new ByteArrayOutputStream();
StreamHandler sh = new StreamHandler(os, NbFormatter.FORMATTER);
DispatchingHandler dh = new DispatchingHandler(sh, 10);
dh.setFormatter(my);
dh.publish(new LogRecord(Level.WARNING, "Ahoj"));
dh.flush();
String res = new String(os.toByteArray(), "UTF-8");
assertEquals("Only the message is written", "Ahoj", res);
assertEquals("Called once", 1, my.cnt);
}
private SystemLogger(String name, String rootpath, String logFilePattern, int logBufferSize, int fileSizeLimit,
int fileCountLimit, boolean append, Formatter format) {
this.filePattern = logFilePattern;
this.fileSizeLimit = fileSizeLimit;
this.fileCountLimit = fileCountLimit;
this.logBufferSize = logBufferSize;
this.shouldAppend = append;
log = new PLogger(name);
log.enableConsoleOut(true);
log.setLogLevel(LogLevel.INFO);
this.logRoot = rootpath + "/logs";
if (!IOHelper.exists(logRoot)) {
IOHelper.createFolder(logRoot);
}
log.enableFileOut(this.logRoot + "/" + this.filePattern, true, this.logBufferSize, this.fileSizeLimit,
this.fileCountLimit, this.shouldAppend, format);
}
@Test
public void testLog() throws Exception {
LogRecord record = new LogRecord(Level.INFO, "test message {0} {1} {2} {3}");
record.setLoggerName("foo.bar");
record.setMillis(0); // epoch
record.setParameters(new Object[] {"arg1", "arg2", "arg3", "arg4"});
record.setSourceClassName(TestYarnWatchdog.class.getName());
record.setSourceMethodName("testLog");
final FutureTask<String> task = new FutureTask<>(()-> {
Formatter formatter = new YarnWatchdog.YarnWatchdogFormatter();
return formatter.format(record);
});
Thread t = new Thread(task, "test-log-thread");
t.start();
String result = task.get(60, TimeUnit.SECONDS); // make sure to have some timeout
// Make sure TZ is set to UTC...
assertThat(result, is(equalTo("1970-01-01 00:00:00,000 [test-log-thread] INFO com.dremio.provision.yarn.TestYarnWatchdog - test message arg1 arg2 arg3 arg4 \n")));
}
/**
* Empty configured values are ignored and the fallback is used instead.
*
* @throws IllegalArgumentException if a formatter object cannot be instantiated from the
* configured class name
*/
private static Formatter getConfiguredFormatterProperty(
Formatter builderValue, String configuredName, Formatter fallbackValue) {
return getConfiguredProperty(
builderValue,
configuredName,
val -> {
val = val.trim();
if (val.length() > 0) {
try {
return (Formatter)
ClassLoader.getSystemClassLoader()
.loadClass(val)
.getDeclaredConstructor()
.newInstance();
} catch (ReflectiveOperationException e) {
throw new IllegalArgumentException(e);
}
} else {
return fallbackValue;
}
},
fallbackValue);
}
@Override
public void publish(LogRecord record) {
// when possible preformat outside synchronized superclass method
// (our most involved UriProcessingFormatter can cache result)
Formatter f = getFormatter();
if(!(f instanceof Preformatter)) {
super.publish(record);
} else {
try {
((Preformatter)f).preformat(record);
super.publish(record);
} finally {
((Preformatter)f).clear();
}
}
}
private static Logger instantiateLogger(final String name, final Level level) {
final Logger logger = java.util.logging.Logger.getLogger(name);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
for (final Handler h : logger.getHandlers()) {
logger.removeHandler(h);
}
logger.setLevel(level);
logger.setUseParentHandlers(false);
final Handler c = new ConsoleHandler();
c.setFormatter(new Formatter() {
@Override
public String format(final LogRecord record) {
final StringBuilder sb = new StringBuilder();
sb.append('[')
.append(record.getLoggerName())
.append("] ")
.append(record.getMessage())
.append('\n');
return sb.toString();
}
});
logger.addHandler(c);
c.setLevel(level);
return null;
}
}, createLoggerControlAccCtxt());
return logger;
}
/**
* Report to the error manager that a logging loop was detected and
* we are going to break the cycle of messages. It is possible that
* a custom error manager could continue the cycle in which case
* we will stop trying to report errors.
* @param record the record or null.
* @since JavaMail 1.4.6
*/
private void reportUnPublishedError(LogRecord record) {
final Integer idx = MUTEX.get();
if (idx == null || idx > MUTEX_REPORT) {
MUTEX.set(MUTEX_REPORT);
try {
final String msg;
if (record != null) {
final Formatter f = createSimpleFormatter();
msg = "Log record " + record.getSequenceNumber()
+ " was not published. "
+ head(f) + format(f, record) + tail(f, "");
} else {
msg = null;
}
Exception e = new IllegalStateException(
"Recursive publish detected by thread "
+ Thread.currentThread());
reportError(msg, e, ErrorManager.WRITE_FAILURE);
} finally {
if (idx != null) {
MUTEX.set(idx);
} else {
MUTEX.remove();
}
}
}
}
@Override
public void setFormatter(final Formatter newFormatter) throws SecurityException {
if (applyLayout) {
final Appender appender = this.appender;
if (appender != null) {
appender.setLayout(new FormatterLayout(newFormatter));
}
}
super.setFormatter(newFormatter);
}
/**
* Sets the attachment file name for each attachment. All control
* characters are removed from the attachment names.
* This method will create a set of custom formatters.
* @param names an array of names.
* @throws SecurityException if a security manager exists and the
* caller does not have <code>LoggingPermission("control")</code>.
* @throws IndexOutOfBoundsException if the number of attachment
* names do not match the number of attachment formatters.
* @throws IllegalArgumentException if any name is empty.
* @throws NullPointerException if any given array or name is
* <code>null</code>.
* @throws IllegalStateException if called from inside a push.
* @see Character#isISOControl(char)
* @see Character#isISOControl(int)
*/
public final void setAttachmentNames(final String... names) {
checkAccess();
final Formatter[] formatters;
if (names.length == 0) {
formatters = emptyFormatterArray();
} else {
formatters = new Formatter[names.length];
}
for (int i = 0; i < names.length; ++i) {
final String name = names[i];
if (name != null) {
if (name.length() > 0) {
formatters[i] = TailNameFormatter.of(name);
} else {
throw new IllegalArgumentException(atIndexMsg(i));
}
} else {
throw new NullPointerException(atIndexMsg(i));
}
}
synchronized (this) {
if (this.attachmentFormatters.length != names.length) {
throw attachmentMismatch(this.attachmentFormatters.length, names.length);
}
if (isWriting) {
throw new IllegalStateException();
}
this.attachmentNames = formatters;
}
}
private static Logger instantiateLogger(final String name, final Level level) {
final Logger logger = java.util.logging.Logger.getLogger(name);
for (final Handler h : logger.getHandlers()) {
logger.removeHandler(h);
}
logger.setLevel(level);
logger.setUseParentHandlers(false);
final Handler c = new ConsoleHandler();
c.setFormatter(new Formatter() {
@Override
public String format(final LogRecord record) {
final StringBuilder sb = new StringBuilder();
sb.append('[')
.append(record.getLoggerName())
.append("] ")
.append(record.getMessage())
.append('\n');
return sb.toString();
}
});
logger.addHandler(c);
c.setLevel(level);
return logger;
}
/**
* Determines the mimeType of a formatter by the class name. This method
* avoids calling getHead and getTail of content formatters during verify
* because they might trigger side effects or excessive work. The name
* formatters and subject are usually safe to call.
* Package-private for unit testing.
*
* @param f the formatter or null.
* @return return the mime type or null, meaning text/plain.
* @since JavaMail 1.5.6
*/
final String contentTypeOf(final Formatter f) {
assert Thread.holdsLock(this);
if (f != null) {
String type = getContentType(f.getClass().getName());
if (type != null) {
return type;
}
for (Class<?> k = f.getClass(); k != Formatter.class;
k = k.getSuperclass()) {
String name;
try {
name = k.getSimpleName();
} catch (final InternalError JDK8057919) {
name = k.getName();
}
name = name.toLowerCase(Locale.ENGLISH);
for (int idx = name.indexOf('$') + 1;
(idx = name.indexOf("ml", idx)) > -1; idx += 2) {
if (idx > 0) {
if (name.charAt(idx - 1) == 'x') {
return "application/xml";
}
if (idx > 1 && name.charAt(idx - 2) == 'h'
&& name.charAt(idx - 1) == 't') {
return "text/html";
}
}
}
}
}
return null;
}
/**
* Creates the formatted log record or reports a formatting error.
* @param f the formatter.
* @param r the log record.
* @return the formatted string or an empty string.
*/
private String format(final Formatter f, final LogRecord r) {
try {
return f.format(r);
} catch (final RuntimeException RE) {
reportError(RE.getMessage(), RE, ErrorManager.FORMAT_FAILURE);
return "";
}
}
public static void init() {
try {
// Create an appending file handler
// Create a file handler that write log record to a file
// pattern - the pattern for naming the output file
// limit - the maximum number of bytes to write to any one file
// count - the number of files to use
// append - specifies append mode
FileHandler fileHandler = new FileHandler(MobydroidStatic.LOG_PATH, LOG_LIMIT, LOG_COUNT, LOG_APPEND);
// create a custom Formatter
fileHandler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
StringBuilder builder = new StringBuilder();
builder.append((new SimpleDateFormat("dd/MM/yyyy hh:mm:ss")).format(new Date(record.getMillis()))).append(" - ");
builder.append("[").append(record.getLevel()).append("] - ");
builder.append(formatMessage(record));
builder.append("\n");
return builder.toString();
}
});
LOGGER.addHandler(fileHandler);
// enable logging
logEnabled = true;
// first test ;)
Log.log(Level.INFO, "Logger", "initialized");
} catch (SecurityException | IOException ex) {
Log.log(Level.SEVERE, "Logger", ex);
}
}
@Test
public void periodicRotatingConfigurationTest() {
Handler handler = getHandler(PeriodicRotatingFileHandler.class);
assertThat(handler.getLevel()).isEqualTo(Level.INFO);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n");
}
@Test
public void periodicSizeRotatingConfigurationTest() {
Handler handler = getHandler(PeriodicSizeRotatingFileHandler.class);
assertThat(handler.getLevel()).isEqualTo(Level.INFO);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n");
PeriodicSizeRotatingFileHandler periodicSizeRotatingFileHandler = (PeriodicSizeRotatingFileHandler) handler;
assertThat(periodicSizeRotatingFileHandler.isRotateOnBoot()).isFalse();
}
@Test
public void sizeRotatingConfigurationTest() {
Handler handler = getHandler(SizeRotatingFileHandler.class);
assertThat(handler.getLevel()).isEqualTo(Level.INFO);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n");
SizeRotatingFileHandler sizeRotatingFileHandler = (SizeRotatingFileHandler) handler;
assertThat(sizeRotatingFileHandler.isRotateOnBoot()).isTrue();
}
@Test
public void periodicSizeRotatingConfigurationTest() {
Handler handler = getHandler(PeriodicSizeRotatingFileHandler.class);
assertThat(handler.getLevel()).isEqualTo(Level.INFO);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n");
PeriodicSizeRotatingFileHandler periodicSizeRotatingFileHandler = (PeriodicSizeRotatingFileHandler) handler;
assertThat(periodicSizeRotatingFileHandler.isRotateOnBoot()).isTrue();
}
@Test
public void consoleOutputTest() {
Handler handler = getHandler(ConsoleHandler.class);
assertThat(handler).isNotNull();
assertThat(handler.getLevel()).isEqualTo(Level.WARNING);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c{3.}] (%t) %s%e%n");
}
private static Logger instantiateLogger(final String name, final Level level) {
final Logger logger = java.util.logging.Logger.getLogger(name);
for (final Handler h : logger.getHandlers()) {
logger.removeHandler(h);
}
logger.setLevel(level);
logger.setUseParentHandlers(false);
final Handler c = new ConsoleHandler();
c.setFormatter(new Formatter() {
@Override
public String format(final LogRecord record) {
final StringBuilder sb = new StringBuilder();
sb.append('[')
.append(record.getLoggerName())
.append("] ")
.append(record.getMessage())
.append('\n');
return sb.toString();
}
});
logger.addHandler(c);
c.setLevel(level);
return logger;
}
BannerFormatter(@NotNull Formatter formatter, boolean isColorPattern, Supplier<String> bannerSupplier) {
this.formatter = formatter;
this.isColorPattern = isColorPattern;
this.bannerSupplier = bannerSupplier;
if (isColorPattern) {
this.setPattern(((ColorPatternFormatter) formatter).getPattern());
} else {
this.setPattern(((PatternFormatter) formatter).getPattern());
}
}
public ResourceUsageAnalyzer(
Set<String> resourcePackages,
@NonNull Path rTxt,
@NonNull Path classes,
@NonNull Path manifest,
@Nullable Path mapping,
@NonNull Path resources,
@Nullable Path logFile)
throws DOMException, ParserConfigurationException {
this.model = new ResourceShrinkerUsageModel();
this.resourcePackages = resourcePackages;
this.rTxt = rTxt;
this.proguardMapping = mapping;
this.classes = classes;
this.mergedManifest = manifest;
this.mergedResourceDir = resources;
this.logger = Logger.getLogger(getClass().getName());
logger.setLevel(Level.FINE);
if (logFile != null) {
try {
FileHandler fileHandler = new FileHandler(logFile.toString());
fileHandler.setLevel(Level.FINE);
fileHandler.setFormatter(
new Formatter() {
@Override
public String format(LogRecord record) {
return record.getMessage() + "\n";
}
});
logger.addHandler(fileHandler);
} catch (SecurityException | IOException e) {
logger.warning(String.format("Unable to open '%s' to write log.", logFile));
}
}
}
private static Logger instantiateLogger(final String name, final Level level) {
final Logger logger = java.util.logging.Logger.getLogger(name);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
for (final Handler h : logger.getHandlers()) {
logger.removeHandler(h);
}
logger.setLevel(level);
logger.setUseParentHandlers(false);
final Handler c = new ConsoleHandler();
c.setFormatter(new Formatter() {
@Override
public String format(final LogRecord record) {
final StringBuilder sb = new StringBuilder();
sb.append('[')
.append(record.getLoggerName())
.append("] ")
.append(record.getMessage())
.append('\n');
return sb.toString();
}
});
logger.addHandler(c);
c.setLevel(level);
return null;
}
}, createLoggerControlAccCtxt());
return logger;
}