Java Code Examples for java.util.logging.Formatter

The following are top voted examples for showing how to use java.util.logging.Formatter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: LogFormatterTest.java   Source Code and License 7 votes vote down vote up
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());
}
 
Example 2
Project: Pogamut3   File: JMXLogPublisher.java   Source Code and License 7 votes vote down vote up
@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
			)
		);
	}
}
 
Example 3
Project: sequence-mining   File: Logging.java   Source Code and License 7 votes vote down vote up
/** 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 4
Project: bisdk   File: Test.java   Source Code and License 7 votes vote down vote up
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);
	}
}
 
Example 5
Project: tomee   File: SimpleTomEEFormatterTest.java   Source Code and License 7 votes vote down vote up
@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);
    }
}
 
Example 6
Project: tomee   File: SimpleTomEEFormatterTest.java   Source Code and License 7 votes vote down vote up
@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);
    }
}
 
Example 7
Project: SES   File: SESLogFormatter.java   Source Code and License 7 votes vote down vote up
/**
 * 
 * @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");
}
 
Example 8
Project: enviroCar-app   File: LocalFileHandler.java   Source Code and License 7 votes vote down vote up
@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;
}
 
Example 9
Project: incubator-netbeans   File: LogFormatterTest.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 10
Project: incubator-netbeans   File: DispatchingHandlerTest.java   Source Code and License 6 votes vote down vote up
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 11
Project: JInsight   File: TracingMetricRegistry.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 12
Project: jtsgen   File: AbstractProcessorWithLogging.java   Source Code and License 6 votes vote down vote up
@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);
        }
    }
 
Example 13
Project: uavstack   File: SystemLogger.java   Source Code and License 6 votes vote down vote up
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 14
Project: scorekeeperfrontend   File: AppSetup.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 15
Project: ColorConsole   File: ColorLogFormatter.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 16
Project: THUTag   File: EntryPoint.java   Source Code and License 6 votes vote down vote up
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";
            }
            
          });
    }
  }

}
 
Example 17
Project: ExilePearl   File: TestServer.java   Source Code and License 6 votes vote down vote up
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);
  }
 
Example 18
Project: icedtea-web   File: LogBasedFileLog.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 19
Project: VarJ   File: Tester.java   Source Code and License 6 votes vote down vote up
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;");
}
 
Example 20
Project: kore-javamail   File: MailHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 21
Project: kore-javamail   File: MailHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 22
Project: kore-javamail   File: MailHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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 "";
    }
}
 
Example 23
Project: kore-javamail   File: CollectorFormatter.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: openwonderland   File: BaseRunner.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 25
Project: lBackup   File: LogCtr.java   Source Code and License 6 votes vote down vote up
/**
 * 
 */
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();
	}
     	
}
 
Example 26
Project: fax4j   File: JDKLogger.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 27
Project: wildfly-logstash   File: SocketHandler.java   Source Code and License 6 votes vote down vote up
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;
  }
}
 
Example 28
Project: daris   File: DataDownload.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 29
Project: syslog-java-client   File: LogManagerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 30
Project: netarchivesuite-svngit-migration   File: CachingLogHandler.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 31
Project: lojix   File: LoggingDiagnostic.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: denovo-variant-caller-java   File: DenovoRunner.java   Source Code and License 6 votes vote down vote up
/** 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;
}
 
Example 33
Project: jcloudscale   File: ServerLogger.java   Source Code and License 6 votes vote down vote up
@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();
	}
}
 
Example 34
Project: bazel   File: ResourceUsageAnalyzer.java   Source Code and License 6 votes vote down vote up
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 35
Project: com.zacwolf.commons.webex   File: ManageDomain.java   Source Code and License 6 votes vote down vote up
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;
	}
 
Example 36
Project: itemset-mining   File: Logging.java   Source Code and License 6 votes vote down vote up
/** 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 37
Project: dbms   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 38
Project: dbms   File: ConsoleHandler.java   Source Code and License 6 votes vote down vote up
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);
}
 
Example 39
Project: dbms   File: LoggerUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example 40
Project: webarchive-commons   File: GenerationFileHandler.java   Source Code and License 6 votes vote down vote up
@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 41
Project: musicmount   File: LoggingUtil.java   Source Code and License 6 votes vote down vote up
static Formatter createFormatter() {
    return new Formatter() {
		final MessageFormat messageFormat = new MessageFormat("{0}{1,date,HH:mm:ss} {2} - {3}{4}\n");
		@Override
		public synchronized String format(LogRecord record) {
			Object[] arguments = new Object[] {
				String.format("%-8s", record.getLevel()),
				new Date(record.getMillis()),
				record.getLoggerName() == null ? "<Unknown Logger>" : record.getLoggerName().substring(record.getLoggerName().lastIndexOf('.') + 1),
				record.getMessage() == null ? "<No Message>" : record.getMessage(),
				record.getThrown() == null ? "" : ", " + record.getThrown()
			};
			return messageFormat.format(arguments);
		}	
	};
}
 
Example 42
Project: cohorte-utilities   File: CXJulUtils.java   Source Code and License 6 votes vote down vote up
/**
 * @param aLogger
 *            The Jul logger to set
 * @param aFormatter
 *            The Jul line formater to apply
 * @return The number of modified handler
 */
public static int setFormatter(final Logger aLogger, final Formatter aFormatter) {

	int wNbSet = 0;
	final Handler[] wHandlers = aLogger.getHandlers();

	if (wHandlers != null && wHandlers.length > 0) {
		for (final Handler wHandler : wHandlers) {
			if (wHandler instanceof ConsoleHandler) {
				wHandler.setFormatter(sSimpleFormatter);
				wNbSet++;
			} else if (wHandler instanceof FileHandler) {
				wHandler.setFormatter(sSimpleFormatter);
				wNbSet++;
			}
		}
	}
	return wNbSet;
}
 
Example 43
Project: QuickServer-Main   File: QuickServer.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the console log handler formatter.
 * @param formatter fully qualified name of the class that implements 
 * {@link java.util.logging.Formatter}
 * @since 1.2
 */
public void setConsoleLoggingFormatter(String formatter) 
		throws ClassNotFoundException, InstantiationException,
			IllegalAccessException {
	if(formatter==null)
		return;
	consoleLoggingformatter = formatter;

	java.util.logging.Formatter conformatter = 
		(java.util.logging.Formatter) getClass(formatter, true).newInstance();
	Logger jdkLogger = Logger.getLogger("");
	Handler[] handlers =  jdkLogger.getHandlers();
	for(int index = 0; index < handlers.length; index++ ) {
		if(ConsoleHandler.class.isInstance(handlers[index])) {
			handlers[index].setFormatter(conformatter);
		}
	}
	logger.log(Level.FINEST, "Set to {0}", formatter);
}
 
Example 44
Project: org.openntf.domino   File: LogFilterHandler.java   Source Code and License 6 votes vote down vote up
private void setUpHandler(final Map.Entry<LogConfig.L_LogHandler, L_HandlerEx> handlerEnt,
		final Map.Entry<LogConfig.L_LogHandler, L_HandlerEx> oldHandlerEnt) throws Exception {
	if (oldHandlerEnt != null)
		if (tryUpdateHandler(handlerEnt, oldHandlerEnt))
			return;
	LogConfig.L_LogHandler handlerCfgEnt = handlerEnt.getKey();
	boolean useDefaultFormatter = (handlerCfgEnt._formatterClass == null);
	try {
		Handler newHandler = (Handler) handlerCfgEnt._handlerGetInstance
				.invoke(null, handlerCfgEnt._handlerConfig, useDefaultFormatter);
		handlerEnt.setValue(new L_HandlerEx(newHandler));
		if (!useDefaultFormatter)
			newHandler.setFormatter((Formatter) handlerCfgEnt._formatterGetInstance.invoke(null));
	} catch (Exception e) {
		System.err.println("Logging: Error setting up Handler " + handlerCfgEnt._handlerClassName);
		throw e;
	}
}
 
Example 45
Project: denominator   File: DenominatorD.java   Source Code and License 6 votes vote down vote up
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 46
Project: incubator-netbeans   File: LogFormatterTest.java   Source Code and License 5 votes vote down vote up
public void testFormatterDoesNotIncludeHashOnButton() throws ClassNotFoundException {
    LogRecord r = new LogRecord(Level.INFO, "BUTTON");
    r.setParameters(new Object[] { new JButton("kuk") });
    Formatter formatter = new LogFormatter();
    String s = formatter.format(r);
    assertEquals("No @\n" + s, -1, s.indexOf("@"));
    if (s.indexOf("kuk") == -1) {
        fail("kuk should be there:\n" + s);
    }
}
 
Example 47
Project: incubator-netbeans   File: LogFormatterTest.java   Source Code and License 5 votes vote down vote up
public void testFormatterDoesNotIncludeHashOnActions() throws ClassNotFoundException {
    LogRecord r = new LogRecord(Level.INFO, "ACTION");
    SA sa = SA.get(SA.class);
    r.setParameters(new Object[] { sa });
    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);
    }
    if (s.indexOf("LogFormatterTest$SA") == -1) {
        fail("LogFormatterTest$SA should be there:\n" + s);
    }
}
 
Example 48
Project: incubator-netbeans   File: LogFormatterTest.java   Source Code and License 5 votes vote down vote up
public void testFormatterDoesNotIncludeHashOnMenu() throws ClassNotFoundException {
    LogRecord r = new LogRecord(Level.INFO, "MENU");
    SA sa = SA.get(SA.class);
    r.setParameters(new Object[] { new JMenuItem(sa) });
    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);
    }
    if (s.indexOf("LogFormatterTest$SA") == -1) {
        fail("LogFormatterTest$SA should be there:\n" + s);
    }
}
 
Example 49
Project: Pogamut3   File: JMXLogPublisher.java   Source Code and License 5 votes vote down vote up
/**
 * Initialize publisher with the simplest formatter - just publishing the message.
 */
public JMXLogPublisher() {
	super(new Formatter(){
		@Override
		public String format(LogRecord record) {				
			return record.getMessage();
		}			
	});
}
 
Example 50
Project: Pogamut3   File: LogPublisher.java   Source Code and License 5 votes vote down vote up
public FilePublisher(File file, Formatter formatter) throws PogamutIOException {
	super(formatter);
	NullCheck.check(file, "file");
	this.file = file;
	FilePath.makeDirsToFile(file);
	try {
		fileOut = new FileOutputStream(file);
	} catch (FileNotFoundException e) {
		throw new PogamutIOException("Can't open file '" + file.getAbsolutePath() + "' for logging.", e);
	}
	fileWriter = new PrintWriter(fileOut);
}
 
Example 51
Project: OpenJSharp   File: DebugLogger.java   Source Code and License 5 votes vote down vote up
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 52
Project: uavstack   File: PLogger.java   Source Code and License 5 votes vote down vote up
@Override
public void enableFileOut(String filepattern, boolean check, int bufferSize, int fileSize, int fileCount,
        boolean isAppend, Formatter format) {

    if (check == true) {

        if (this.fileHandler == null) {
            initFileHandler(filepattern, fileSize, fileCount, isAppend);
        }

        if (this.fileHandler != null) {
            this.fileHandler.setLevel(this.level);
            this.fileHandler.setFormatter(format);
        }

        /**
         * NOTE: we use async log buffer
         */
        if (this.memHandler == null) {
            this.memHandler = new MemoryHandler(this.fileHandler, bufferSize, this.level);
            this.log.addHandler(this.memHandler);
        }
    }
    else {
        if (this.memHandler != null) {
            log.removeHandler(this.memHandler);
        }
    }
}
 
Example 53
Project: skeletoid   File: LogFileAppender.java   Source Code and License 5 votes vote down vote up
@Override
public void enableAppender(final Context context) {
    final int MBYTE_IN_BYTES = 1024 * 1024;

    mFileLoggingTP = ThreadPoolUtils.getFixedThreadPool("LogToFileTP", 1);

    mFileLoggingTP.submit(new Runnable() {
        @Override
        public void run() {
            try {
                mFileHandler = new FileHandler(getFileLogPath(context),
                        mLogFileSize * MBYTE_IN_BYTES, mNumberOfLogFiles, true);
                mFileHandler.setFormatter(new SimpleFormatter());
                mFileHandler.setFormatter(new Formatter() {
                    @Override
                    public String format(LogRecord logRecord) {
                        return logRecord.getMessage() + "\n";
                    }
                });

                mCanWriteToFile = true;

            } catch (Throwable e) {
                mCanWriteToFile = false;
                LOG.e(LOG_TAG, e, "Logging to file startup error");
            }
        }
    });

}
 
Example 54
Project: openjdk-jdk10   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(Handler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType) {
    checkEquals(handler, "level", handler.getLevel(), expectedLevel);
    checkEquals(handler, "encoding", handler.getEncoding(), expectedEncoding);
    checkType(handler, "filter", handler.getFilter(), expectedFilterType);
    checkType(handler, "formatter", handler.getFormatter(), expectedFormatterType);
}
 
Example 55
Project: openjdk-jdk10   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(MemoryHandler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType,
           Class<? extends Handler> expextedTargetType,
           int expextedSize,
           Level expectedPushLevel) {
    checkType(handler, "target", getTarget(handler), expextedTargetType);
    checkEquals(handler, "size", getSize(handler), expextedSize);
    checkEquals(handler, "pushLevel", handler.getPushLevel(), expectedPushLevel);
    check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType);
}
 
Example 56
Project: openjdk-jdk10   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(StreamHandler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType,
           OutputStream expectedOutputStream) {
    checkEquals(handler, "outputStream", getOutput(handler), expectedOutputStream);
    check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType);
}
 
Example 57
Project: openjdk-jdk10   File: DebugLogger.java   Source Code and License 5 votes vote down vote up
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 58
Project: openjdk9   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(Handler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType) {
    checkEquals(handler, "level", handler.getLevel(), expectedLevel);
    checkEquals(handler, "encoding", handler.getEncoding(), expectedEncoding);
    checkType(handler, "filter", handler.getFilter(), expectedFilterType);
    checkType(handler, "formatter", handler.getFormatter(), expectedFormatterType);
}
 
Example 59
Project: openjdk9   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(MemoryHandler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType,
           Class<? extends Handler> expextedTargetType,
           int expextedSize,
           Level expectedPushLevel) {
    checkType(handler, "target", getTarget(handler), expextedTargetType);
    checkEquals(handler, "size", getSize(handler), expextedSize);
    checkEquals(handler, "pushLevel", handler.getPushLevel(), expectedPushLevel);
    check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType);
}
 
Example 60
Project: openjdk9   File: HandlersConfigTest.java   Source Code and License 5 votes vote down vote up
void check(StreamHandler handler,
           Level expectedLevel,
           String expectedEncoding,
           Class<? extends Filter> expectedFilterType,
           Class<? extends Formatter> expectedFormatterType,
           OutputStream expectedOutputStream) {
    checkEquals(handler, "outputStream", getOutput(handler), expectedOutputStream);
    check(handler, expectedLevel, expectedEncoding, expectedFilterType, expectedFormatterType);
}