本文整理汇总了Java中java.util.logging.Formatter类的典型用法代码示例。如果您正苦于以下问题:Java Formatter类的具体用法?Java Formatter怎么用?Java Formatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Formatter类属于java.util.logging包,在下文中一共展示了Formatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testUnknownLevels
import java.util.logging.Formatter; //导入依赖的package包/类
public void testUnknownLevels() throws IOException {
TestLevel level = new TestLevel("WARN", 233);
LogRecord r = new LogRecord(level, "Custom level test");
Formatter formatter = new LogFormatter();
String s = formatter.format(r);
cleanKnownLevels();
final LogRecord[] rPtr = new LogRecord[] { null };
Handler h = new Handler() {
@Override
public void publish(LogRecord record) {
rPtr[0] = record;
}
@Override
public void flush() {}
@Override
public void close() throws SecurityException {}
};
LogRecords.scan(new ReaderInputStream(new StringReader(s)), h);
assertEquals("level", r.getLevel(), rPtr[0].getLevel());
}
示例2: publish
import java.util.logging.Formatter; //导入依赖的package包/类
@Override
public void publish(LogRecord record) {
Formatter actualFormatter = formatter;
if (actualFormatter != null) {
String message = actualFormatter.format(record);
notification.sendNotification(
new JMXLogRecordNotification(
objectName,
sequenceNumber++,
record.getMillis(),
message,
record
)
);
}
}
示例3: setUpConsoleHandler
import java.util.logging.Formatter; //导入依赖的package包/类
/** 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;
}
示例4: initLog
import java.util.logging.Formatter; //导入依赖的package包/类
private static void initLog()
{
Formatter simpleFormatter;
try
{
String path = new File(".").getCanonicalPath();
String logName = String.valueOf(System.currentTimeMillis());
simpleFormatter = new SimpleFormatter();
fileHandler = new FileHandler(path + logName + ".log");
fileHandler.setFormatter(simpleFormatter);
fileHandler.setLevel(Level.ALL);
}
catch (IOException e)
{
errorLog.log(Level.WARNING, e.getMessage(), e);
}
}
示例5: formatNullThrown
import java.util.logging.Formatter; //导入依赖的package包/类
@Test
public void formatNullThrown() throws Exception {
final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);
try {
final String lineSeparatorValue = "\n";
final String logMessage = "An example log record";
final Level level = Level.FINEST;
System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
final LogRecord logRecordInput = new LogRecord(level, logMessage);
logRecordInput.setThrown(null);
final Formatter formatter = new SimpleTomEEFormatter();
final String actualFormatOutput = formatter.format(logRecordInput);
final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + "\n";
assertEquals(expectedFormatOutput, actualFormatOutput);
} finally {
System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
}
}
示例6: formatNotNullThrown
import java.util.logging.Formatter; //导入依赖的package包/类
@Test
public void formatNotNullThrown() throws Exception {
final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);
try {
final String lineSeparatorValue = "\n";
final String logMessage = "An example log record";
final Level level = Level.CONFIG;
final String exceptionMessage = "An example exception";
final Throwable thrown = new Exception(exceptionMessage);
System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
final LogRecord logRecordInput = new LogRecord(level, logMessage);
logRecordInput.setThrown(thrown);
final Formatter formatter = new SimpleTomEEFormatter();
final String actualFormatOutput = formatter.format(logRecordInput);
final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue + ExceptionUtils.getStackTrace(thrown);
assertEquals(expectedFormatOutput, actualFormatOutput);
} finally {
System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
}
}
示例7: main
import java.util.logging.Formatter; //导入依赖的package包/类
/**
*
* @param args the
*/
public static void main(String[] args) {
Logger logger = Logger.getLogger("test");
logger.info("test");
logger.addHandler(new ConsoleHandler());
logger.info("tes");
Formatter f = new SESLogFormatter("prefix");
Handler[] handlers = logger.getHandlers();
Handler handler;
logger.info("" + handlers.length);
for (int i = 0; i < handlers.length; i++) {
handler = handlers[i];
handler.setFormatter(f);
}
logger.info("test2");
}
示例8: createHandler
import java.util.logging.Formatter; //导入依赖的package包/类
@SuppressLint("SimpleDateFormat")
protected FileHandler createHandler(String finalPath) throws IOException {
FileHandler h = new FileHandler(finalPath, MAX_SIZE, 3, true);
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
final String sep = System.getProperty("line.separator");
h.setFormatter(new Formatter() {
@Override
public String format(LogRecord r) {
String date = format.format(new Date(r.getMillis()));
return String.format(Locale.US, "%s [%s]: (%d) %s%s", date, r.getLevel(), r.getThreadID(), r.getMessage(), sep);
}
});
h.setLevel(Level.ALL);
return h;
}
示例9: testFormatterDoesNotIncludeHashOnEditor
import java.util.logging.Formatter; //导入依赖的package包/类
public void testFormatterDoesNotIncludeHashOnEditor() throws ClassNotFoundException {
LogRecord r = new LogRecord(Level.INFO, "EDIT");
JEditorPane ep = new javax.swing.JEditorPane();
ep.setName("SomeName");
r.setParameters(new Object[] { ep });
Formatter formatter = new LogFormatter();
String s = formatter.format(r);
assertEquals("No @\n" + s, -1, s.indexOf("@"));
if (s.indexOf("SomeName") == -1) {
fail("SomeName should be there:\n" + s);
}
}
示例10: testOwnFormatter
import java.util.logging.Formatter; //导入依赖的package包/类
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);
}
示例11: createMetricUpdateTracer
import java.util.logging.Formatter; //导入依赖的package包/类
private static Logger createMetricUpdateTracer() {
Logger logger = Logger.getLogger(TracingMetricRegistry.class.getName() + ".metricUpdates");
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return ">>" + record.getMessage() + "\n";
}
});
logger.addHandler(handler);
logger.setUseParentHandlers(false);
handler.setLevel(Level.ALL);
//logger.setLevel(Level.ALL);
return logger;
}
示例12: init
import java.util.logging.Formatter; //导入依赖的package包/类
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
final Optional<String> jtsgenLogLevel = Optional.ofNullable(processingEnv.getOptions().get("jtsgenLogLevel"));
String packageName = AbstractProcessorWithLogging.class.getPackage().getName();
final Logger logger = Logger.getLogger(packageName);
if (jtsgenLogLevel.isPresent()) {
Level level = jtsgenLogLevel
.map(
(x) -> {
try {
return Level.parse(x.trim().toUpperCase());
} catch (IllegalArgumentException ex) {
return Level.OFF;
}
}
).orElse(Level.INFO);
Formatter oneLineFormatter = new OneLineFormatter();
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(level);
consoleHandler.setFormatter(oneLineFormatter);
logger.setUseParentHandlers(false);
logger.setLevel(level);
// consoleHandler.setFormatter(oneLineFormatter);
logger.addHandler(consoleHandler);
LOG.log(Level.FINER,() -> String.format("LogLevel %s = %s ", packageName, level.getName()));
} else {
logger.setLevel(Level.OFF);
}
}
示例13: SystemLogger
import java.util.logging.Formatter; //导入依赖的package包/类
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);
}
示例14: appSetup
import java.util.logging.Formatter; //导入依赖的package包/类
/**
* Do some common setup for all applications at startup
* @param name the application name used for Java logging and database logging
*/
public static void appSetup(String name)
{
// Set our platform wide L&F
System.setProperty("swing.defaultlaf", "javax.swing.plaf.nimbus.NimbusLookAndFeel");
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
defaults.put("Table.gridColor", new Color(140,140,140));
defaults.put("Table.showGrid", true);
// Set the program name which is used by PostgresqlDatabase to identify the app in logs
System.setProperty("program.name", name);
// Start with a fresh root set at warning
Logger root = LogManager.getLogManager().getLogger("");
Formatter format = new SingleLineFormatter();
root.setLevel(Level.WARNING);
for(Handler handler : root.getHandlers()) {
root.removeHandler(handler);
}
// Set prefs levels before windows preference load barfs useless data on the user
Logger.getLogger("java.util.prefs").setLevel(Level.SEVERE);
// postgres JDBC spits out a lot of data even though we catch the exception
Logger.getLogger("org.postgresql.jdbc").setLevel(Level.OFF);
Logger.getLogger("org.postgresql.Driver").setLevel(Level.OFF);
// Add console handler if running in debug mode
if (Prefs.isDebug()) {
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.ALL);
ch.setFormatter(format);
root.addHandler(ch);
}
// For our own logs, we can set super fine level or info depending on if debug mode and attach dialogs to those
Logger applog = Logger.getLogger("org.wwscc");
applog.setLevel(Prefs.isDebug() ? Level.FINEST : Level.INFO);
applog.addHandler(new AlertHandler());
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
applog.log(Level.WARNING, String.format("\bUncaughtException in %s: %s", t, e), e);
}});
try {
File logdir = Prefs.getLogDirectory().toFile();
if (!logdir.exists())
if (!logdir.mkdirs())
throw new IOException("Can't create log directory " + logdir);
FileHandler fh = new FileHandler(new File(logdir, name+".%g.log").getAbsolutePath(), 1000000, 10, true);
fh.setFormatter(format);
fh.setLevel(Level.ALL);
root.addHandler(fh);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(FocusManager.getCurrentManager().getActiveWindow(),
"Unable to enable logging to file: " + ioe, "Log Error", JOptionPane.ERROR_MESSAGE);
}
// force the initialization of IdGenerator on another thread so app can start now without an odd delay later
new Thread() {
public void run() {
IdGenerator.generateId();
}
}.start();
}
示例15: ColorLogFormatter
import java.util.logging.Formatter; //导入依赖的package包/类
public ColorLogFormatter(ColorConsoleBungee plugin, Formatter oldFormatter) {
this.plugin = plugin;
this.oldFormatter = oldFormatter;
List<String> ignoreMessages = plugin.getConfiguration().getStringList("hide-messages");
boolean colorizeTag = plugin.getConfiguration().getBoolean("colorPluginTag");
boolean truncateColor = plugin.getConfiguration().getBoolean("truncateColor", false);
Map<String, String> levelColors = Maps.newHashMap();
if (plugin.getConfiguration().getBoolean("colorMessage", false)) {
levelColors.put("FATAL", plugin.getConfiguration().getString("FATAL"));
levelColors.put("ERROR", plugin.getConfiguration().getString("ERROR"));
levelColors.put("WARN", plugin.getConfiguration().getString("WARN"));
levelColors.put("DEBUG", plugin.getConfiguration().getString("DEBUG"));
levelColors.put("TRACE", plugin.getConfiguration().getString("TRACE"));
}
this.formatter = new CommonFormatter(ignoreMessages, colorizeTag, truncateColor, levelColors);
}