Java 类java.util.logging.Formatter 实例源码
项目:incubator-netbeans
文件:LogFormatterTest.java
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());
}
项目:Pogamut3
文件:JMXLogPublisher.java
@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
)
);
}
}
项目:sequence-mining
文件:Logging.java
/** 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;
}
项目:bisdk
文件:Test.java
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);
}
}
项目:tomee
文件:SimpleTomEEFormatterTest.java
@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);
}
}
项目:tomee
文件:SimpleTomEEFormatterTest.java
@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);
}
}
项目:SES
文件:SESLogFormatter.java
/**
*
* @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");
}
项目:enviroCar-app
文件:LocalFileHandler.java
@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;
}
项目:incubator-netbeans
文件:LogFormatterTest.java
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);
}
}
项目:incubator-netbeans
文件:DispatchingHandlerTest.java
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);
}
项目:JInsight
文件:TracingMetricRegistry.java
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;
}
项目:jtsgen
文件:AbstractProcessorWithLogging.java
@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);
}
}
项目:uavstack
文件:SystemLogger.java
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);
}
项目:scorekeeperfrontend
文件:AppSetup.java
/**
* 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();
}
项目:ColorConsole
文件:ColorLogFormatter.java
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);
}
项目:THUTag
文件:EntryPoint.java
public static void setLogFormat() {
Logger root = Logger.getLogger("");
Handler [] handlers = root.getHandlers(); // returns 1
for (int i = 0; i < handlers.length; i++) {
if (handlers[i] instanceof ConsoleHandler) {
((ConsoleHandler)handlers[i])
.setFormatter(new Formatter() {
public SimpleDateFormat format =
new SimpleDateFormat("yy/MM/dd HH:mm:ss");
public String format(LogRecord record) {
Date d = new Date(record.getMillis());
return format.format(d) + " " + record.getMessage() + "\n";
}
});
}
}
}
项目:ExilePearl
文件:TestServer.java
public void configureLogger(boolean useLogger) {
if (this.useLogger != useLogger && logger != null) {
return;
}
this.useLogger = useLogger;
if (useLogger) {
logger = Logger.getLogger(serverName);
} else {
logger = Mockito.mock(Logger.class);
return;
}
// Format the logger output
Formatter formatter = new Formatter() {
private final DateFormat df = new SimpleDateFormat("hh:mm:ss");
@Override
public String format(LogRecord record) {
String level = record.getLevel().getLocalizedName().toUpperCase();
if (level.equals("WARNING")) {
level = "WARN";
}
Throwable thrown = record.getThrown();
if (thrown != null) {
thrown.printStackTrace();
}
return String.format("[%s %s]: %s\n", df.format(new Date(record.getMillis())), level, formatMessage(record));
}
};
logger.setUseParentHandlers(false);
ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter(formatter);
logger.addHandler(handler);
}
项目:icedtea-web
文件:LogBasedFileLog.java
public LogBasedFileLog(String loggerName, String fileName, boolean append) {
try {
File futureFile = new File(fileName);
if (!futureFile.exists()) {
FileUtils.createRestrictedFile(futureFile, true);
}
fh = new FileHandler(fileName, append);
fh.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return record.getMessage() + "\n";
}
});
impl = Logger.getLogger(loggerName);
impl.setLevel(Level.ALL);
impl.addHandler(fh);
log(FileLog.getHeadlineHeader().toString() + " log-based impl.");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
项目:VarJ
文件:Tester.java
public static void main(String[] args)
{
if (args.length < 1) {
System.err.println("usage: java backend.logging.Tester <verbosity level>");
System.exit(1);
}
int vlevel = Integer.parseInt(args[0]);
Level level = VarLogger.getLogLevel(vlevel);
Formatter formatter = VarLogger.canHandleColor() ?
new RenameLevelFormatter(
RenameLevelFormatter.ColorNameStrategy.getInstance())
: new SimpleFormatter();
Logger LOG = new VarLogger.FormatterBuilder()
.formatter(formatter)
.level(level)
.build()
.getLogger();
System.out.println("Log level: " + LOG.getLevel());
LOG.log(ERROR, "A error message;");
LOG.log(INFO, "An info message;");
LOG.log(DEBUG, "A debug message;");
}
项目:kore-javamail
文件:MailHandler.java
/**
* Sets the attachment <tt>Formatter</tt> 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 <tt>LoggingPermission("control")</tt>.
* @throws NullPointerException if the given array or any array index is
* <tt>null</tt>.
* @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 = 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.fixUpAttachmentFilters();
this.fixUpAttachmentNames();
}
}
项目:kore-javamail
文件:MailHandler.java
/**
* Sets the attachment file name formatters. The format method of each
* attachment formatter will see only the <tt>LogRecord</tt> objects that
* passed its attachment filter during formatting. The format method will
* typically return an empty string. Instead of being used to format
* records, it is used to gather information about the contents of an
* attachment. The <tt>getTail</tt> method should be used to construct the
* attachment file name and reset any formatter collected state. The
* formatter must ensure that the attachment file name does not contain any
* line breaks. The <tt>toString</tt> method of the given formatter should
* be overridden to provide a useful attachment file name, if possible.
* @param formatters and array of attachment name formatters.
* @throws SecurityException if a security manager exists and the
* caller does not have <tt>LoggingPermission("control")</tt>.
* @throws IndexOutOfBoundsException if the number of attachment
* name formatters do not match the number of attachment formatters.
* @throws NullPointerException if any given array or name is <tt>null</tt>.
* @throws IllegalStateException if called from inside a push.
* @see Character#isISOControl(char)
* @see Character#isISOControl(int)
*/
public final void setAttachmentNames(Formatter... formatters) {
checkAccess();
formatters = 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 (this.attachmentFormatters.length != formatters.length) {
throw attachmentMismatch(this.attachmentFormatters.length, formatters.length);
}
if (isWriting) {
throw new IllegalStateException();
}
this.attachmentNames = formatters;
}
}
项目:kore-javamail
文件:MailHandler.java
/**
* 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 "";
}
}
项目:kore-javamail
文件:CollectorFormatter.java
/**
* Gets and creates the formatter from the LogManager or creates the default
* formatter.
*
* @param p the class name prefix.
* @return the formatter.
* @throws UndeclaredThrowableException if the formatter can not be created.
*/
private Formatter initFormatter(final String p) {
final LogManager m = LogManagerProperties.getLogManager();
Formatter f;
String v = m.getProperty(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;
}
项目:openwonderland
文件:BaseRunner.java
/**
* Get a log handler that should be used to write the log out to
* the log file.
* @return the handler to use
*/
protected Handler getLogFileHandler() throws IOException {
logFileHandler = new FileHandler(getLogFile().getCanonicalPath());
logFileHandler.setLevel(Level.ALL);
logFileHandler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return record.getMessage() + "\n";
}
});
return logFileHandler;
}
项目:lBackup
文件:LogCtr.java
/**
*
*/
public LogCtr() {
logger = Logger.getLogger("lbackup");
try{
fh = new FileHandler(PATH_LOG, true);
logger.addHandler(fh);
//SimpleFormatter formatter = new SimpleFormatter();
fh.setFormatter(new Formatter() {
@Override
public String format(LogRecord r) {
Date date = new Date();
date.setTime(r.getMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return "[" + dateFormat.format(date) + "] " + r.getMessage() + "\r\n";
}
});
}catch(Exception e){
e.printStackTrace();
}
}
项目:fax4j
文件:JDKLogger.java
/**
* This function initializes and returns the logger.
*
* @return The logger
*/
protected static final Logger initializeLogger()
{
//get logger
Logger logger=Logger.getLogger(FaxClient.class.getName());
//enable all log events (fax4j logger filters out uneeded log events)
logger.setLevel(Level.ALL);
logger.setFilter(null);
//enable to pass log events to parent loggers
logger.setUseParentHandlers(true);
//create handler
Formatter formatter=new SimpleFormatter();
Handler handler=new StreamHandler(System.out,formatter);
//set filtering
handler.setLevel(logger.getLevel());
handler.setFilter(logger.getFilter());
//add handler
logger.addHandler(handler);
return logger;
}
项目:wildfly-logstash
文件:SocketHandler.java
private String createFormattedMessage(final ExtLogRecord record) {
final Formatter formatter = getFormatter();
try {
return formatter.format(record);
} catch (Exception e) {
reportError("Could not format message", e, ErrorManager.FORMAT_FAILURE);
return null;
}
}
项目:daris
文件:DataDownload.java
public static Logger createLogger() {
Logger logger = Logger.getLogger(APP_NAME);
logger.setLevel(Level.ALL);
logger.setUseParentHandlers(false);
/*
* add file handler
*/
try {
FileHandler fileHandler = new FileHandler("%t/" + APP_NAME + ".%g.log", 5000000, 2);
fileHandler.setLevel(Level.ALL);
fileHandler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(new Date(record.getMillis())).append(" ");
sb.append("[thread: ").append(record.getThreadID()).append("] ");
sb.append(record.getLevel().getName()).append(" ");
sb.append(record.getMessage());
sb.append("\n");
return sb.toString();
}
});
logger.addHandler(fileHandler);
} catch (Throwable e) {
System.err.println("Warning: failed to create daris-download.*.log file in system temporary directory.");
e.printStackTrace(System.err);
return null;
}
return logger;
}
项目:syslog-java-client
文件:LogManagerHelper.java
/**
* 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) {
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;
}
项目:netarchivesuite-svngit-migration
文件:CachingLogHandler.java
/**
* Package private method to get a formatter property. 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.
*
* This method was copied from java.util.logging.LogManager, where it is
* package private :-(
*
* @param name The log property name
* @param defaultValue The formatter if that property is not specified or
* unparsable
* @return The formatter from the property if set and parsable, the
* defaultValue otherwise
*/
@SuppressWarnings("rawtypes")
private Formatter getFormatterProperty(String name,
Formatter defaultValue) {
String val = LogManager.getLogManager().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;
}
项目:lojix
文件:LoggingDiagnostic.java
/**
* Lists information about logging handlers.
*
* @param handlers The handlers.
* @param buffer A string buffer to build up the listing in.
*
* @return The string buffer to build up the listing in.
*/
private static StringBuffer listHandlers(Handler[] handlers, StringBuffer buffer)
{
for (Handler handler : handlers)
{
Class<? extends Handler> handlerClass = handler.getClass();
Formatter formatter = handler.getFormatter();
buffer.append("Handler:").append(handlerClass.getName()).append("\n");
buffer.append("Level:").append(handler.getLevel().toString()).append("\n");
if (formatter != null)
{
buffer.append("Formatter:").append(formatter.getClass().getName()).append("\n");
}
}
return buffer;
}
项目:denovo-variant-caller-java
文件:DenovoRunner.java
/** Set up the logger. Creates a new one each time.
* @param cmdLine
* @return the logger
* @throws IOException
*/
private Logger setUpLogger(CommandLine cmdLine) throws IOException {
if (LogManager.getLogManager().getLogger(DenovoRunner.class.getName()) != null) {
return LogManager.getLogManager().getLogger(DenovoRunner.class.getName());
}
Logger logger = Logger.getLogger(DenovoRunner.class.getName());
ConsoleHandler consoleHandler = new ConsoleHandler();
logger.setLevel(cmdLine.logLevel.getLevel());
logger.setUseParentHandlers(false);
Formatter conciseFormat = new Formatter(){
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(DenovoUtil.LogLevel.levelMap.get(record.getLevel()));
sb.append(" : ");
sb.append(record.getMessage());
sb.append("\n");
return sb.toString();
}
};
consoleHandler.setFormatter(conciseFormat);
consoleHandler.setLevel(cmdLine.logLevel.getLevel());
logger.addHandler(consoleHandler);
if (cmdLine.logFile != null) {
FileHandler fileHandler = new FileHandler(
DenovoUtil.getNormalizedFile(cmdLine.logFile).getAbsolutePath(), false);
fileHandler.setFormatter(conciseFormat);
fileHandler.setLevel(cmdLine.logLevel.getLevel());
logger.addHandler(fileHandler);
}
return logger;
}
项目:jcloudscale
文件:ServerLogger.java
@Override
public void publish(LogRecord record) {
Formatter formatter = getFormatter();
if(formatter == null)
formatter = new ServerLogFormatter();
if(!successfullyInit) {
System.err.println(formatter.format(record));
return;
}
try {
LogObject log = new LogObject();
log.setFormatted(formatter.format(record));
log.setRecord(record);
mq.oneway(log);
System.err.println(formatter.format(record));
} catch (JMSException e) {
e.printStackTrace();
}
}
项目:bazel
文件:ResourceUsageAnalyzer.java
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));
}
}
}
项目:com.zacwolf.commons.webex
文件:ManageDomain.java
public ManageDomain(final String domain,
final String wapiAUTHURL,
final String wapiUSER,
final String wapiPASS,
final String ldapURL,
final String ldapUSER,
final String ldapPASS,
final Properties jobprops
) throws WBXCONexception{
this.DOMAIN = domain;
this.LOGGER = Logger.getLogger(this.DOMAIN);
this.LOGGER.setUseParentHandlers(false);
final Handler defaultHandler = new ConsoleHandler();
final Formatter defaultFormatter = new DomainLoggingFormatter();
defaultHandler.setFormatter(defaultFormatter);
this.LOGGER.addHandler(defaultHandler);
this.org = new _WBXCONfactory(this.DOMAIN,wapiAUTHURL, wapiUSER, wapiPASS);
this.props = jobprops;
if (ldapURL!=null)
this.ldap = new LDAPserverConnection(ldapURL,ldapUSER,ldapPASS);
else this.ldap = null;
}
项目:itemset-mining
文件:Logging.java
/** 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;
}
项目:dbms
文件:Utils.java
/**
* Utility to wait for completion of futures.
*
* @param futures the futures to wait for
* @param logger used to report any error messages
*/
static void checkFutures(List<Future<MessageExchange>> futures,
Logger logger,
EnvironmentImpl envImpl,
Formatter formatter) {
for (final Future<MessageExchange> f : futures) {
new WithFutureExceptionHandler () {
@Override
protected void processFuture ()
throws ExecutionException, InterruptedException {
f.get();
}
}.execute(logger, envImpl, formatter);
}
}
项目:dbms
文件:ConsoleHandler.java
public ConsoleHandler(Formatter formatter, EnvironmentImpl envImpl) {
super();
/* Messages may be formatted with an environment specific tag. */
setFormatter(formatter);
Level level = null;
String propertyName = getClass().getName() + ".level";
if (envImpl != null) {
level =
LoggerUtils.getHandlerLevel(envImpl.getConfigManager(),
EnvironmentParams.JE_CONSOLE_LEVEL,
propertyName);
} else {
/* If envImpl instance is null, level is decided by properties. */
String levelProperty = LoggerUtils.getLoggerProperty(propertyName);
if (levelProperty == null) {
level = Level.OFF;
} else {
level = Level.parse(levelProperty);
}
}
setLevel(level);
}
项目:dbms
文件:LoggerUtils.java
/**
* Log a message with this logger. This utility method should be used in
* tandem with loggers obtained via getLoggerFormatterNeeded() to ensure
* that the thread specific Formatter is pushed before logging, and cleared
* afterwards.
*/
public static void logMsg(Logger useLogger,
Formatter formatter,
Level logLevel,
String msg) {
/* Set thread specific Formatter. */
if (formatter != null) {
formatterMap.put(Thread.currentThread(), formatter);
}
try {
useLogger.log(logLevel, msg);
} finally {
/* Clear thread specific Formatter. */
formatterMap.remove(Thread.currentThread());
}
}
项目:webarchive-commons
文件:GenerationFileHandler.java
@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();
}
}
}