java.util.logging.Formatter Java Examples
The following examples show how to use
java.util.logging.Formatter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoggingJsonRecorder.java From quarkus with Apache License 2.0 | 6 votes |
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)); }
Example #2
Source File: SimpleLogHandler.java From bazel with Apache License 2.0 | 6 votes |
/** * 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); }
Example #3
Source File: DenominatorD.java From denominator with Apache License 2.0 | 6 votes |
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); } }
Example #4
Source File: TestYarnWatchdog.java From dremio-oss with Apache License 2.0 | 6 votes |
@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"))); }
Example #5
Source File: GenerationFileHandler.java From webarchive-commons with Apache License 2.0 | 6 votes |
@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(); } } }
Example #6
Source File: MailHandler.java From FairEmail with GNU General Public License v3.0 | 6 votes |
/** * 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(); } }
Example #7
Source File: SystemLogger.java From uavstack with Apache License 2.0 | 6 votes |
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); }
Example #8
Source File: DispatchingHandlerTest.java From netbeans with Apache License 2.0 | 6 votes |
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); }
Example #9
Source File: Logging.java From sequence-mining with GNU General Public License v3.0 | 6 votes |
/** 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; }
Example #10
Source File: CollectorFormatter.java From FairEmail with GNU General Public License v3.0 | 6 votes |
/** * 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; }
Example #11
Source File: DebugLog.java From bartworks with MIT License | 6 votes |
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; }
Example #12
Source File: LogManagerHelper.java From syslog-java-client with MIT License | 6 votes |
/** * 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; }
Example #13
Source File: JsonFormatterDefaultConfigTest.java From quarkus with Apache License 2.0 | 6 votes |
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; }
Example #14
Source File: DebugLogger.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
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; }
Example #15
Source File: LogFileHandlerTestCase.java From vespa with Apache License 2.0 | 5 votes |
@Test public void testcompression() throws InterruptedException, IOException { File root = temporaryFolder.newFolder("testcompression"); LogFileHandler h = new LogFileHandler(true); h.setFilePattern(root.getAbsolutePath() + "/logfilehandlertest.%Y%m%d%H%M%S%s"); h.setFormatter(new Formatter() { public String format(LogRecord r) { DateFormat df = new SimpleDateFormat("yyyy.MM.dd:HH:mm:ss.SSS"); String timeStamp = df.format(new Date(r.getMillis())); return ("["+timeStamp+"]" + " " + formatMessage(r) + "\n"); } } ); int logEntries = 10000; for (int i = 0; i < logEntries; i++) { LogRecord lr = new LogRecord(Level.INFO, "test"); h.publish(lr); } h.waitDrained(); String f1 = h.getFileName(); assertThat(f1).startsWith(root.getAbsolutePath() + "/logfilehandlertest."); File uncompressed = new File(f1); File compressed = new File(f1 + ".gz"); assertThat(uncompressed).exists(); assertThat(compressed).doesNotExist(); String content = IOUtils.readFile(uncompressed); assertThat(content).hasLineCount(logEntries); h.rotateNow(); while (uncompressed.exists()) { Thread.sleep(1); } assertThat(compressed).exists(); String unzipped = IOUtils.readAll(new InputStreamReader(new GZIPInputStream(new FileInputStream(compressed)))); assertThat(content).isEqualTo(unzipped); h.shutdown(); }
Example #16
Source File: LogFilterHandler.java From org.openntf.domino with Apache License 2.0 | 5 votes |
L_HandlerUpdateEntry(final LogHandlerUpdateIF oldHandlerUIF, final Map.Entry<LogConfig.L_LogHandler, L_HandlerEx> newHandlerEnt, final L_HandlerEx oldHex, final LogHandlerConfigIF newHandlerConfig, final LogHandlerConfigIF oldHandlerConfig, final boolean useDefaultFormatter, final Formatter newFormatter) { _oldHandlerUIF = oldHandlerUIF; _newHandlerEnt = newHandlerEnt; _oldHex = oldHex; _newHandlerConfig = newHandlerConfig; _oldHandlerConfig = oldHandlerConfig; _useDefaultFormatter = useDefaultFormatter; _newFormatter = newFormatter; }
Example #17
Source File: MemoryLogHandler.java From RipplePower with Apache License 2.0 | 5 votes |
/** * Return the log messages from the ring buffer * * @return List of log messages */ public List<String> getMessages() { List<String> rtnList = new ArrayList<>(buffer.length); synchronized (buffer) { int pos = start; Formatter formatter = getFormatter(); for (int i = 0; i < count; i++) { rtnList.add(formatter.format(buffer[pos++])); if (pos == buffer.length) pos = 0; } } return rtnList; }
Example #18
Source File: DebugLogger.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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; }
Example #19
Source File: Logging.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
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; }
Example #20
Source File: DebugLogger.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
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; }
Example #21
Source File: PythonProject.java From AndroidRobot with Apache License 2.0 | 5 votes |
private static final void replaceAllLogFormatters(Formatter form, Level level) /* */ { /* 179 */ LogManager mgr = LogManager.getLogManager(); /* 180 */ Enumeration loggerNames = mgr.getLoggerNames(); /* 181 */ while (loggerNames.hasMoreElements()) { /* 182 */ String loggerName = (String)loggerNames.nextElement(); /* 183 */ Logger logger = mgr.getLogger(loggerName); /* 184 */ for (Handler handler : logger.getHandlers()) { /* 185 */ handler.setFormatter(form); /* 186 */ handler.setLevel(level); /* */ } /* */ } /* */ }
Example #22
Source File: ResourceUsageAnalyzer.java From bazel with Apache License 2.0 | 5 votes |
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)); } } }
Example #23
Source File: LogHandlerConsole.java From org.openntf.domino with Apache License 2.0 | 5 votes |
@Override public void doUpdateYourself(final LogHandlerConfigIF newhandlerConfig, final LogHandlerConfigIF oldHandlerConfig, final boolean useDefaultFormatter, final Formatter newFormatter) { if (newFormatter != null) { setFormatter(newFormatter); } else if (useDefaultFormatter && !(getFormatter() instanceof LogFormatterConsoleDefault)) { setFormatter(new LogFormatterConsoleDefault()); } }
Example #24
Source File: BannerFormatter.java From quarkus with Apache License 2.0 | 5 votes |
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()); } }
Example #25
Source File: PeriodicSizeRotatingLoggingRotateOnBootTest.java From quarkus with Apache License 2.0 | 5 votes |
@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(); }
Example #26
Source File: Logging.java From nashorn with GNU General Public License v2.0 | 5 votes |
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; }
Example #27
Source File: ConsoleHandlerTest.java From quarkus with Apache License 2.0 | 5 votes |
@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"); }
Example #28
Source File: SizeRotatingLoggingTest.java From quarkus with Apache License 2.0 | 5 votes |
@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(); }
Example #29
Source File: PeriodicSizeRotatingLoggingTest.java From quarkus with Apache License 2.0 | 5 votes |
@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(); }
Example #30
Source File: DebugLogger.java From hottub with GNU General Public License v2.0 | 5 votes |
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; }