Java Code Examples for java.util.logging.ConsoleHandler

The following are top voted examples for showing how to use java.util.logging.ConsoleHandler. 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: Dist_HW_2   File: Server.java   Source Code and License 16 votes vote down vote up
public Server(String fileName, boolean restart) {
	super();
	parseServerFile(fileName);
	seatAssignments = new ArrayList<>(nSeats);
	for (int i = 0; i < nSeats; i++)
		seatAssignments.add("");

	log.getParent().removeHandler(log.getParent().getHandlers()[0]);
	
	try {
		// check if logs dir exists
		File logDir = new File("./logs/"); 
		if( !(logDir.exists()) )
			logDir.mkdir();
			
		FileHandler fh = new FileHandler("logs/server_log_" + serverID + ".log");
		fh.setFormatter(new SimpleFormatter());
		fh.setLevel(logLevel);
		log.addHandler(fh);
		
		ConsoleHandler ch = new ConsoleHandler();
		ch.setLevel(logLevel);
		log.addHandler(ch);
		log.setLevel(logLevel);
		
		log.info("Server initializing...");
		log.info("ServerID = " + serverID);
		log.info("nServers = " + nServers);
		log.info("nSeats = " + nSeats);
		log.info("my tcp port = " + tcpPort);
		for (int i = 0; i < nServers; i++)
			log.info("Server " + i + ": " + servers.get(i) + ":" + ports.get(i));
		log.info("Server init complete");
		log.info("--------------------------------");
		mutex = new LamportMutex(servers, ports, this, restart);
		mutex.init();
	} catch (SecurityException | IOException e) {
		e.printStackTrace();
	}
}
 
Example 2
Project: scorekeeperfrontend   File: AppSetup.java   Source Code and License 8 votes vote down vote up
public static void unitLogging()
{
    // Start with a fresh root set at warning
    Logger root = LogManager.getLogManager().getLogger("");
    root.setLevel(Level.WARNING);
    for(Handler handler : root.getHandlers()) { root.removeHandler(handler); }

    //Logger.getLogger("java.util.prefs").setLevel(Level.SEVERE);
    Logger.getLogger("org.postgresql.jdbc").setLevel(Level.OFF);
    Logger.getLogger("org.postgresql.Driver").setLevel(Level.OFF);
    Logger.getLogger("org.wwscc").setLevel(Level.ALL);
    
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.ALL);
    ch.setFormatter(new SingleLineFormatter());
    root.addHandler(ch);
}
 
Example 3
Project: majordodo   File: RestartBrokerAndStartWorkerTest.java   Source Code and License 8 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 4
Project: incubator-netbeans   File: TopLoggingNbLoggerConsoleTest.java   Source Code and License 7 votes vote down vote up
private void doDeadlockConsoleAndStdErr(final ConsoleHandler ch) {
    class H extends Handler implements Runnable {
        public void publish(LogRecord record) {
            try {
                RequestProcessor.getDefault().post(this).waitFinished(100);
            } catch (InterruptedException ex) {
                // ex.printStackTrace();
            }
        }

        public void flush() {
        }

        public void close() throws SecurityException {
        }
        
        public void run() {
            ch.publish(new LogRecord(Level.WARNING, "run"));
        }
    }
    H handler = new H();
    Logger.getLogger("stderr").addHandler(handler);
    
    System.err.println("Ahoj");
}
 
Example 5
Project: monarch   File: LogWrapper.java   Source Code and License 7 votes vote down vote up
private static void addDefaultConsoleHandler(Logger logger, String errorMessage,
    String logFilePath) {
  ConsoleHandler consoleHandler = new ConsoleHandler();
  consoleHandler.setFormatter(new GemFireFormatter());
  logger.addHandler(consoleHandler);

  System.err
      .println("ERROR: Could not log to file: " + logFilePath + ". Reason: " + errorMessage);
  System.err.println("Logs will be written on Console.");
  try {
    Thread.sleep(3000); // sleep for 3 secs for the message to appear
  } catch (InterruptedException ignore) {
  }
}
 
Example 6
Project: OpenCyclos   File: LoggingHandlerImpl.java   Source Code and License 7 votes vote down vote up
/**
 * Creates a new logger
 */
private Logger init(final Level level, final String file) {
    final LogSettings logSettings = settingsService.getLogSettings();
    final Logger logger = Logger.getAnonymousLogger();
    logger.setLevel(level);
    logger.setUseParentHandlers(false);
    try {
        final FileUnits units = logSettings.getMaxLengthPerFileUnits();
        final FileHandler fileHandler = new FileHandler(file, units.calculate(logSettings.getMaxLengthPerFile()), logSettings.getMaxFilesPerLog(), true);
        fileHandler.setFormatter(logFormatter);
        fileHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        logger.addHandler(fileHandler);
    } catch (final Exception e) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(logFormatter);
        try {
            consoleHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        } catch (final Exception e1) {
            // Just ignore
        }
        logger.addHandler(consoleHandler);
        logger.log(Level.WARNING, "Unable to create logger for file " + file);
    }
    return logger;
}
 
Example 7
Project: noa-libre   File: OfficeBeanTest.java   Source Code and License 7 votes vote down vote up
/**
 * Main entry point for the OpenOffice.org Bean Test.
 *
 * @param args arguments of the test
 *
 * @author Andreas Bröker
 * @date 21.05.2006
 */
public static void main(String[] args) throws OfficeApplicationException {

   LogManager.getLogManager().reset();
   ConsoleHandler consoleHandler = new ConsoleHandler();
   consoleHandler.setLevel(Level.FINEST);
   LOGGER.addHandler(consoleHandler);
   LOGGER.setLevel(Level.FINEST);

   try {
      FileHandler fileHandler = new FileHandler("log.xml");
      fileHandler.setLevel(Level.FINEST);
      LOGGER.addHandler(fileHandler);
   } catch (Throwable throwable) {
   }
   OfficeBeanTest testOfficeBean = new OfficeBeanTest();

   if (args.length == 0) {
      testOfficeBean.test(null);
   }else if (args.length == 1) {
      testOfficeBean.test(args[0]);
   }else if(args.length==4){
      testOfficeBean.remoteTestPDF(new File(args[2]), new File(args[3]), args[0], Integer.valueOf(args[1]));
   }else{
      System.out.println("usage:\nOfficeBeanTest host port source-odt target-pdf\nOfficeBeanTest officeHome");
   }
}
 
Example 8
Project: blazingcache   File: JSRExamplesTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 9
Project: majordodo   File: KerberosSimpleBrokerStatusReplicationTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 10
Project: majordodo   File: BrokerStatusReplicationWithLedgerDeletionTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 11
Project: majordodo   File: SimpleBrokerStatusReplicationKerberosTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 12
Project: majordodo   File: AcquireLeadershipTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 13
Project: majordodo   File: SimpleCodePoolTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 14
Project: majordodo   File: HttpClientLeaderRecoveryTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.SEVERE;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 15
Project: majordodo   File: SlotsReleaseTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 16
Project: majordodo   File: ExpireMultipleTasksTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 17
Project: majordodo   File: TaskDeadlineWithoutRequestTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 18
Project: majordodo   File: TaskExecutionRecoveryOnErrorTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 19
Project: majordodo   File: MaxTasksPerUserTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 20
Project: majordodo   File: TaskExecutionSendAgainFinishedNotificationTest.java   Source Code and License 7 votes vote down vote up
@Before
public void setupLogger() throws Exception {
    Level level = Level.INFO;
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
        }
    });
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(level);
    SimpleFormatter f = new SimpleFormatter();
    ch.setFormatter(f);
    java.util.logging.Logger.getLogger("").setLevel(level);
    java.util.logging.Logger.getLogger("").addHandler(ch);
}
 
Example 21
Project: j2objc   File: ConsoleHandlerTest.java   Source Code and License 7 votes vote down vote up
public void testConstructor_InvalidProperties() throws Exception {
	Properties p = new Properties();
	p.put("java.util.logging.ConsoleHandler.level", INVALID_LEVEL);
	p.put("java.util.logging.ConsoleHandler.filter", className);
	p.put("java.util.logging.ConsoleHandler.formatter", className);
	p.put("java.util.logging.ConsoleHandler.encoding", "XXXX");
	LogManager.getLogManager().readConfiguration(
			EnvironmentHelper.PropertiesToInputStream(p));

	assertEquals(LogManager.getLogManager().getProperty(
			"java.util.logging.ConsoleHandler.level"), INVALID_LEVEL);
	assertEquals(LogManager.getLogManager().getProperty(
			"java.util.logging.ConsoleHandler.encoding"), "XXXX");
	ConsoleHandler h = new ConsoleHandler();
	assertSame(h.getLevel(), Level.INFO);
	assertTrue(h.getFormatter() instanceof SimpleFormatter);
	assertNull(h.getFilter());
	assertNull(h.getEncoding());
	h.publish(new LogRecord(Level.SEVERE, "test"));
	assertNull(h.getEncoding());
}
 
Example 22
Project: j2objc   File: ConsoleHandlerTest.java   Source Code and License 7 votes vote down vote up
public void testPublish_AfterResetSystemErr() throws Exception {
	Properties p = new Properties();
	p.put("java.util.logging.ConsoleHandler.formatter", className
			+ "$MockFormatter");
	LogManager.getLogManager().readConfiguration(
			EnvironmentHelper.PropertiesToInputStream(p));
	ConsoleHandler h = new ConsoleHandler();
	h.setFilter(new MockFilter());

	System.setErr(new PrintStream(new ByteArrayOutputStream()));

	LogRecord r = new LogRecord(Level.INFO, "testPublish_WithFilter");
	h.setLevel(Level.INFO);
	h.publish(r);
	assertNull(CallVerificationStack.getInstance().pop());
	assertSame(r, CallVerificationStack.getInstance().pop());
	assertEquals("", this.errSubstituteStream.toString());
}
 
Example 23
Project: Ogar2-Server   File: OgarServer.java   Source Code and License 7 votes vote down vote up
private void setupLogging() {
    log.setUseParentHandlers(false);

    LogFormatter formatter = new LogFormatter();

    ConsoleHandler ch = new ConsoleHandler();
    ch.setFormatter(formatter);
    if (isDebugging()) {
        log.setLevel(Level.FINEST);
        ch.setLevel(Level.FINEST);
    } else {
        log.setLevel(Level.INFO);
        ch.setLevel(Level.INFO);
    }
    log.addHandler(ch);

    try {
        FileHandler fh = new FileHandler("server.log");
        fh.setFormatter(formatter);
        if (isDebugging()) {
            fh.setLevel(Level.FINEST);
        } else {
            ch.setLevel(Level.INFO);
        }
        log.addHandler(fh);
    } catch (IOException ex) {
        log.log(Level.SEVERE, "Error while adding FileHandler to logger. Logs will not be output to a file.", ex);
    }

}
 
Example 24
Project: Reer   File: JULRedirector.java   Source Code and License 6 votes vote down vote up
@Override
public StandardOutputCapture start() {
    super.start();
    boolean shouldReadLoggingConfigFile = System.getProperty(READ_LOGGING_CONFIG_FILE_PROPERTY, "true").equals("true");
    if (!shouldReadLoggingConfigFile) {
        SingleMessageLogger.nagUserOfDiscontinuedProperty(READ_LOGGING_CONFIG_FILE_PROPERTY,
            "Change your test to work with your java.util.logging configuration file settings.");
    }
    if (!reset) {
        LogManager.getLogManager().reset();
        if (shouldReadLoggingConfigFile) {
            try {
                LogManager.getLogManager().readConfiguration();
            } catch (IOException error) {
                Logger.getLogger("").addHandler(new ConsoleHandler());
            }
        } else {
            Logger.getLogger("").addHandler(new ConsoleHandler());
        }
        reset = true;
    }
    return this;
}
 
Example 25
Project: GitHub   File: Main.java   Source Code and License 6 votes vote down vote up
private static void enableHttp2FrameLogging() {
  frameLogger = Logger.getLogger(Http2.class.getName());
  frameLogger.setLevel(Level.FINE);
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.FINE);
  handler.setFormatter(new SimpleFormatter() {
    @Override public String format(LogRecord record) {
      return Util.format("%s%n", record.getMessage());
    }
  });
  frameLogger.addHandler(handler);
}
 
Example 26
Project: GitHub   File: Main.java   Source Code and License 6 votes vote down vote up
private static void enableHttp2FrameLogging() {
  frameLogger = Logger.getLogger(Http2.class.getName());
  frameLogger.setLevel(Level.FINE);
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.FINE);
  handler.setFormatter(new SimpleFormatter() {
    @Override public String format(LogRecord record) {
      return Util.format("%s%n", record.getMessage());
    }
  });
  frameLogger.addHandler(handler);
}
 
Example 27
Project: launcher-backend   File: LoggingConfig.java   Source Code and License 6 votes vote down vote up
public LoggingConfig() {
    try {
        // Load a properties file from class path java.util.logging.config.file
        final LogManager logManager = LogManager.getLogManager();
        URL configURL = getClass().getResource("/logging.properties");
        if (configURL != null) {
            try (InputStream is = configURL.openStream()) {
                logManager.readConfiguration(is);
            }
        } else {
            // Programmatic configuration
            System.setProperty("java.util.logging.SimpleFormatter.format",
                               "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n");

            final ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINEST);
            consoleHandler.setFormatter(new SimpleFormatter());

            final Logger app = Logger.getLogger("app");
            app.setLevel(Level.FINEST);
            app.addHandler(consoleHandler);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 28
Project: Pogamut3   File: ServerRunner.java   Source Code and License 6 votes vote down vote up
/**
 * Constructor.
 */
public ServerRunner() {
    log.setLevel(Level.ALL); 
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(new SimpleFormatter());
    handler.setLevel(Level.ALL);
    log.addHandler(handler);

}
 
Example 29
Project: Pogamut3   File: Test00_SingleMultiWVTest.java   Source Code and License 6 votes vote down vote up
public void setUp()
{
	agentId = new TeamedAgentId("Agent01");
	agentId.setTeamId( new TeamId("teamRED"));
	agentLogger = new AgentLogger(agentId);
	LifecycleBus bus = new LifecycleBus(agentLogger);
	
	Logger sharedLogger = Logger.getLogger("SharedLogger");
	sharedLogger.addHandler( new ConsoleHandler() );
	sharedLogger.setLevel( Level.INFO );
	agentLogger.setLevel(Level.INFO);
	agentLogger.addDefaultConsoleHandler();
	
	sharedWV = new EventDrivenSharedWorldViewStub( sharedLogger );
	
	ComponentStub starter = new ComponentStub(agentLogger, bus);
	
	localWV = new EventDrivenLocalWorldViewStub( new ComponentDependencies( ComponentDependencyType.STARTS_WITH ).add(starter), bus, agentLogger, sharedWV, agentId);
	
	starter.getController().manualStart("TEST");
	localWV.setCurrentTime( TimeKey.get(0));
}
 
Example 30
Project: Pogamut3   File: Test01_SharedWorldViewMultiAgent.java   Source Code and License 6 votes vote down vote up
public static void createShared()
{
	globalLogger = Logger.getLogger("globalLogger");
	ConsoleHandler handler = new ConsoleHandler();
	globalLogger.addHandler(handler);
	handler.setLevel(Level.INFO);
	//LogFormatter formatter = new LogFormatter();
	//handler.setFormatter(formatter);
	globalLogger.setLevel( Level.INFO );
	sharedWV = new EventDrivenSharedWorldViewStub(globalLogger);
}
 
Example 31
Project: bitbox   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Logger log = Logger.getGlobal();
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    log.addHandler(handler);
    log.setLevel(Level.ALL);
    JFrame fra = new JFrame("bitbox");
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    BaseConverter baseConverter = new BaseConverter();
    BitCombiner bitCombiner = new BitCombiner();
    BitPainter bitPainter = new BitPainter();
    SwingUtilities.invokeLater(() -> {
        fra.setSize(new Dimension(500, screenSize.height));
        fra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        fra.setLayout(new GridLayout(GRID_SIZE, GRID_SIZE));
        fra.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
        fra.add(baseConverter);
        fra.add(bitCombiner);
        fra.add(bitPainter);
        fra.setVisible(true);
        log.fine("Created GUI");
    });
}
 
Example 32
Project: Racter   File: Log.java   Source Code and License 6 votes vote down vote up
/**
 * Configure Logger
 *
 * @throws IOException
 */
protected void config() throws IOException
{
    if( Boolean.parseBoolean(this.config.get("log_console_status", "false")) ){
        consoleHandler = new ConsoleHandler();
        log.addHandler(consoleHandler);
        if( this.config.get("log_console_level", "SEVERE").equals("ALL") ){
            consoleHandler.setLevel(Level.ALL);
        }else if( this.config.get("log_console_level", "SEVERE").equals("CONFIG") ){
            consoleHandler.setLevel(Level.CONFIG);
        }else if( this.config.get("log_console_level", "SEVERE").equals("FINE") ){
            consoleHandler.setLevel(Level.FINE);
        }else if( this.config.get("log_console_level", "SEVERE").equals("FINER") ){
            consoleHandler.setLevel(Level.FINER);
        }else if( this.config.get("log_console_level", "SEVERE").equals("FINEST") ){
            consoleHandler.setLevel(Level.FINEST);
        }else if( this.config.get("log_console_level", "SEVERE").equals("INFO") ){
            consoleHandler.setLevel(Level.INFO);
        }else if( this.config.get("log_console_level", "SEVERE").equals("OFF") ){
            consoleHandler.setLevel(Level.OFF);
        }else if( this.config.get("log_console_level", "SEVERE").equals("SEVERE") ){
            consoleHandler.setLevel(Level.SEVERE);
        }else if( this.config.get("log_console_level", "SEVERE").equals("WARNING") ){
            consoleHandler.setLevel(Level.WARNING);
        }
    }

    if( Boolean.parseBoolean(this.config.get("log_file_status", "false")) ){
        fileHandler  = new FileHandler(this.config.get("log_file_path", "src/main/java/resources/app.log"),
            Integer.parseInt(this.config.get("log_file_limit", "1")),
            Integer.parseInt(this.config.get("log_file_count", "200000")),
            Boolean.parseBoolean(this.config.get("log_file_append", "true"))
        );
        log.addHandler(fileHandler);
        if( this.config.get("log_file_level", "SEVERE").equals("ALL") ){
            fileHandler.setLevel(Level.ALL);
        }else if( this.config.get("log_file_level", "SEVERE").equals("CONFIG") ){
            fileHandler.setLevel(Level.CONFIG);
        }else if( this.config.get("log_file_level", "SEVERE").equals("FINE") ){
            fileHandler.setLevel(Level.FINE);
        }else if( this.config.get("log_file_level", "SEVERE").equals("FINER") ){
            fileHandler.setLevel(Level.FINER);
        }else if( this.config.get("log_file_level", "SEVERE").equals("FINEST") ){
            fileHandler.setLevel(Level.FINEST);
        }else if( this.config.get("log_file_level", "SEVERE").equals("INFO") ){
            fileHandler.setLevel(Level.INFO);
        }else if( this.config.get("log_file_level", "SEVERE").equals("OFF") ){
            fileHandler.setLevel(Level.OFF);
        }else if( this.config.get("log_file_level", "SEVERE").equals("SEVERE") ){
            fileHandler.setLevel(Level.SEVERE);
        }else if( this.config.get("log_file_level", "SEVERE").equals("WARNING") ){
            fileHandler.setLevel(Level.WARNING);
        }
    }
}
 
Example 33
Project: information-retrieval   File: Log.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize the logger
 */
public static void init() {

    ConsoleHandler handler = new ConsoleHandler();
    // PUBLISH this level
    handler.setLevel(Level.FINEST);
    LOGGER.addHandler(handler);
    LOGGER.setLevel(Level.FINEST);
}
 
Example 34
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 35
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 36
Project: Example.EMA.Java.SpeedGuide   File: SpeedGuideConsumer.java   Source Code and License 6 votes vote down vote up
public void setDebug(boolean debug)
{
	_debug = debug;
	_consumerClient.setDebug(debug);

	if (!debug)
	{
		final Logger parentLogger = Logger.getAnonymousLogger().getParent();

		// Disable console logger if debug mode not turned on
		for (Handler handler : parentLogger.getHandlers())
		{
			if ( handler instanceof ConsoleHandler )
				parentLogger.removeHandler(handler);
		}
	}
}
 
Example 37
Project: uavstack   File: PLogger.java   Source Code and License 6 votes vote down vote up
@Override
public void enableConsoleOut(boolean check) {

    if (check == true) {
        if (this.consoleHandler == null) {
            this.consoleHandler = new ConsoleHandler();
            this.consoleHandler.setLevel(this.level);
            this.consoleHandler.setFormatter(new DefaultLogFormatter());
        }
        log.addHandler(this.consoleHandler);
    }
    else {
        if (this.consoleHandler != null) {
            log.removeHandler(this.consoleHandler);
        }
    }
}
 
Example 38
Project: Kyoko   File: Kyoko.java   Source Code and License 6 votes vote down vote up
public void start() throws LoginException, InterruptedException, RateLimitedException {
    running = true;

    // init logger
    AnsiConsole.systemInstall();
    log = Logger.getLogger("Kyoko");
    log.setUseParentHandlers(false);
    ColoredFormatter formatter = new ColoredFormatter();
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(formatter);
    log.addHandler(handler);

    log.info("Kyoko v" + Constants.VERSION + " is starting...");

    i18n.loadMessages();

    JDABuilder builder = new JDABuilder(AccountType.BOT);
    if (settings.getToken() != null) {
        if (settings.getToken().equalsIgnoreCase("Change me")) {
            System.out.println("No token specified, please set it in config.json");
            System.exit(1);
        }
        builder.setToken(settings.getToken());
    }

    boolean gameEnabled = false;
    if (settings.getGame() != null && !settings.getGame().isEmpty()) {
        gameEnabled = true;
        builder.setGame(Game.of("booting..."));
    }

    builder.setAutoReconnect(true);
    builder.setBulkDeleteSplittingEnabled(false);
    builder.addEventListener(eventHandler);
    builder.setAudioEnabled(true);
    builder.setStatus(OnlineStatus.IDLE);
    jda = builder.buildBlocking();

    log.info("Invite link: " + "https://discordapp.com/oauth2/authorize?&client_id=" + jda.getSelfUser().getId() + "&scope=bot&permissions=" + Constants.PERMISSIONS);

    if (gameEnabled) {
        Thread t = new Thread(new Kyoko.BlinkThread());
        t.start();
    }

    registerCommands();
}
 
Example 39
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 40
Project: jboss-eap7.1-playground   File: AbstractLoggerMain.java   Source Code and License 6 votes vote down vote up
static private void setLogging(int logging) {
		Level logLevel = getLogLevel(logging%10);

		Logger.getLogger("org.jboss.wfink.eap71.playground").setLevel(logLevel);

		logLevel = getLogLevel((logging/10)%10);
		Logger.getLogger("org.xnio").setLevel(logLevel);
		Logger.getLogger("org.jboss.remoting").setLevel(logLevel);	//classes are remoting3
		
		logLevel = getLogLevel((logging/100)%10);
		Logger.getLogger("org.jboss.ejb.client").setLevel(logLevel);
		
		logLevel = getLogLevel((logging/1000)%10);
		Logger.getLogger("org.wildfly").setLevel(logLevel);
		
//		Logger.getLogger("org.jboss.invocation").setLevel(logLevel);

		// change default ConsoleHandler
		Logger root = Logger.getLogger("");
		Handler[] handlers = root.getHandlers();
		for (int i = 0; i < handlers.length; i++) {
			root.removeHandler(handlers[i]);
		}
		ConsoleHandler handler = new ConsoleHandler();
		handler.setFormatter(new PlaygroundFormatter());
		handler.setLevel(Level.ALL);
		root.addHandler(handler);
	}
 
Example 41
Project: openjdk9   File: Security.java   Source Code and License 6 votes vote down vote up
public static void initServer() throws Exception {
    String portstring = System.getProperty("port.number");
    port = portstring != null ? Integer.parseInt(portstring) : 0;
    portstring = System.getProperty("port.number1");
    proxyPort = portstring != null ? Integer.parseInt(portstring) : 0;

    Logger logger = Logger.getLogger("com.sun.net.httpserver");
    ConsoleHandler ch = new ConsoleHandler();
    logger.setLevel(Level.ALL);
    ch.setLevel(Level.ALL);
    logger.addHandler(ch);
    String root = System.getProperty ("test.src")+ "/docs";
    InetSocketAddress addr = new InetSocketAddress (port);
    s1 = HttpServer.create (addr, 0);
    if (s1 instanceof HttpsServer) {
        throw new RuntimeException ("should not be httpsserver");
    }
    HttpHandler h = new FileServerHandler (root);
    HttpContext c = s1.createContext ("/files", h);

    HttpHandler h1 = new RedirectHandler ("/redirect");
    HttpContext c1 = s1.createContext ("/redirect", h1);

    executor = Executors.newCachedThreadPool();
    s1.setExecutor (executor);
    s1.start();

    if (port == 0)
        port = s1.getAddress().getPort();
    else {
        if (s1.getAddress().getPort() != port)
            throw new RuntimeException("Error wrong port");
        System.out.println("Port was assigned by Driver");
    }
    System.out.println("HTTP server port = " + port);
    httproot = "http://127.0.0.1:" + port + "/files/";
    redirectroot = "http://127.0.0.1:" + port + "/redirect/";
    uri = new URI(httproot);
    fileuri = httproot + "foo.txt";
}
 
Example 42
Project: java-tcp   File: JLogger.java   Source Code and License 6 votes vote down vote up
static public void setup() throws IOException {

        // Get root logger object
        Logger rootLogger = Logger.getLogger("");
        rootLogger.removeHandler(rootLogger.getHandlers()[0]);

        // Create new ConsoleHandler
        ConsoleHandler ch = new ConsoleHandler();
        ch.setLevel(Level.FINEST);
        ch.setFormatter(new LoggerFormat());

        // Add handler to logger and set level
        rootLogger.addHandler(ch);
        rootLogger.setLevel(Level.FINEST);
    }
 
Example 43
Project: PriorityOkHttp   File: Main.java   Source Code and License 6 votes vote down vote up
private static void enableHttp2FrameLogging() {
  Logger logger = Logger.getLogger(Http2.class.getName() + "$FrameLogger");
  logger.setLevel(Level.FINE);
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.FINE);
  handler.setFormatter(new SimpleFormatter() {
    @Override public String format(LogRecord record) {
      return String.format("%s%n", record.getMessage());
    }
  });
  logger.addHandler(handler);
}
 
Example 44
Project: yajsw   File: OutLogger.java   Source Code and License 6 votes vote down vote up
public OutLogger(String name, boolean stateOnly)
{
	super(name);
	_name = name;
	_stateOnly = stateOnly;
	Logger logger = Logger.getLogger(name);
	if (!isNew(logger))
		return;
	Logger.getLogger(name).setLevel(Level.ALL);
	ConsoleHandler console = new ConsoleHandler();
	console.setLevel(Level.ALL);
	console.setFormatter(new SimpleFormatter()
	{
		public synchronized String format(LogRecord record)
		{
			return System.currentTimeMillis() + " (" + _name + ") "
					+ record.getMessage() + "\r\n";
		}
	});
	Logger.getLogger(name).addHandler(console);
}
 
Example 45
Project: rb-bi   File: RbLogger.java   Source Code and License 6 votes vote down vote up
public static Logger getLogger(String loggerName) {
    Logger logger = Logger.getLogger(loggerName);
    logger.setUseParentHandlers(false);

    RbFormatter formatter = new RbFormatter();
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(formatter);

    logger.addHandler(handler);

    return logger;
}
 
Example 46
Project: rb-bi   File: RbLogger.java   Source Code and License 6 votes vote down vote up
public static Logger getLogger(String loggerName) {
    Logger logger = Logger.getLogger(loggerName);
    logger.setUseParentHandlers(false);

    RbFormatter formatter = new RbFormatter();
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(formatter);

    logger.addHandler(handler);

    return logger;
}
 
Example 47
Project: FatJar   File: FLogger.java   Source Code and License 6 votes vote down vote up
public static Logger getLogger(String name) {
    Logger logger = Logger.getLogger(name);
    // do not use parent handlers
    logger.setUseParentHandlers(false);
    // if there are any, remove them
    for (Handler handler : logger.getHandlers()) {
        // remove already registered handlers
        logger.removeHandler(handler);
    }
    // add new console handler
    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setFormatter(new FLogFormatter());
    logger.addHandler(consoleHandler);
    return logger;
}
 
Example 48
Project: gemfirexd-oss   File: LogWrapper.java   Source Code and License 6 votes vote down vote up
private static void addDefaultConsoleHandler(Logger logger, String errorMessage, String logFilePath) {
  ConsoleHandler consoleHandler = new ConsoleHandler();
  consoleHandler.setFormatter(new GemFireFormatter());
  logger.addHandler(consoleHandler);

  System.err.println("ERROR: Could not log to file: " + logFilePath + ". Reason: " + errorMessage);
  System.err.println("Logs will be written on Console.");
  try {
    Thread.sleep(3000); //sleep for 3 secs for the message to appear
  } catch (InterruptedException ignore) {}
}
 
Example 49
Project: PhET   File: TestCanvas.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args){
    JmeFormatter formatter = new JmeFormatter();

    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setFormatter(formatter);

    Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]);
    Logger.getLogger("").addHandler(consoleHandler);
    
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            JPopupMenu.setDefaultLightWeightPopupEnabled(false);

            createFrame();
            createCanvas(appClass);
            
            frame.getContentPane().add(canvas);
            frame.pack();
            startApp();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}
 
Example 50
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 51
Project: CurseLib   File: CurseClient.java   Source Code and License 6 votes vote down vote up
private CurseClient() throws SecurityException, IOException {
    File f = new File(USERDATA_PATH + "logs");
    if (!f.exists()) f.mkdirs();
    
    ConsoleHandler ch = new ConsoleHandler();
    ch.setFormatter(new SimpleFormatter());
    FileHandler fh = new FileHandler(USERDATA_PATH + "logs" + File.separator + "%u.%g.log",
            1024 * 1024, 10, false);
    fh.setFormatter(new SimpleFormatter());

    Log.getLogger().getLogger().setUseParentHandlers(false);
    Log.getLogger().getLogger().addHandler(fh);
    Log.getLogger().getLogger().addHandler(ch);
    Log.info("CurseClient initialised.");
}
 
Example 52
Project: launchpad-missioncontrol   File: LoggingConfig.java   Source Code and License 6 votes vote down vote up
public LoggingConfig() {
    try {
        // Load a properties file from class path java.util.logging.config.file
        final LogManager logManager = LogManager.getLogManager();
        URL configURL = getClass().getResource("/logging.properties");
        if (configURL != null) {
            try (InputStream is = configURL.openStream()) {
                logManager.readConfiguration(is);
            }
        } else {
            // Programmatic configuration
            System.setProperty("java.util.logging.SimpleFormatter.format",
                               "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] %5$s %6$s%n");

            final ConsoleHandler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINEST);
            consoleHandler.setFormatter(new SimpleFormatter());

            final Logger app = Logger.getLogger("app");
            app.setLevel(Level.FINEST);
            app.addHandler(consoleHandler);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 53
Project: turnus   File: Logger.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize the logger. All the attached appenders are closed and the log
 * level is initialized to {@link Level#INFO}
 */
public static void init() {
	if (logger != null) {
		for (Handler h : Arrays.asList(logger.getHandlers())) {
			logger.removeHandler(h);
			h.close();
		}
	}

	ConsoleHandler handler = new BlackConsoleHandler();
	handler.setFormatter(new DefaultFormatter());

	logger = java.util.logging.Logger.getLogger("exelixi logger");
	logger.addHandler(handler);
	logger.setUseParentHandlers(false);
	setVerbose(false);
}
 
Example 54
Project: bessemer   File: Compiler.java   Source Code and License 6 votes vote down vote up
private static void setupLogger() {
    Logger rootLogger = Logger.getLogger("com");
    rootLogger.setUseParentHandlers(false);

    Handler[] handlers = rootLogger.getHandlers();
    for(Handler handler : handlers) {
        if(handler.getClass() == ConsoleHandler.class) {
            rootLogger.removeHandler(handler);
        }
    }

    ConsoleHandler console = new ConsoleHandler();
    console.setLevel(logLevel);
    rootLogger.addHandler(console);

    rootLogger.setLevel(logLevel);
}
 
Example 55
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 56
Project: nomulus   File: ProxyModule.java   Source Code and License 6 votes vote down vote up
/**
 * Enable FINE level logging.
 *
 * <p>Set the loggers log level to {@code FINE}, and also add a console handler that actually
 * output {@code FINE} level messages to stdout. The handler filters out all non FINE level log
 * record to avoid double logging. Log records at level higher than FINE (e. g. INFO) will be
 * handled at parent loggers. Note that {@code FINE} level corresponds to {@code DEBUG} level in
 * Netty.
 */
private static void enableDebugLevelLogging() {
  ImmutableList<Logger> parentLoggers =
      ImmutableList.of(
          Logger.getLogger("io.netty.handler.logging.LoggingHandler"),
          // Parent of all FormattingLoggers, so that we do not have to configure each
          // FormattingLogger individually.
          Logger.getLogger("google.registry.proxy"));
  for (Logger logger : parentLoggers) {
    logger.setLevel(Level.FINE);
    Handler handler = new ConsoleHandler();
    handler.setFilter(record -> Objects.equals(record.getLevel(), Level.FINE));
    handler.setLevel(Level.FINE);
    logger.addHandler(handler);
  }
}
 
Example 57
Project: gwt-syncproxy   File: FixedAndroidHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Ensures that only 1 FixedAndroidHandler exists per logger and by default
 * removes any installed {@link ConsoleHandler}. Use
 * {@link #setDisableConsoleHandler(boolean)} to change that option
 *
 * @param logger
 */
public static void setupLogger(Logger logger) {
	Handler[] handlers = logger.getHandlers();
	boolean newHandler = true;
	for (Handler handler : handlers) {
		if (handler instanceof FixedAndroidHandler) {
			newHandler = false;
		}
		if (handler instanceof ConsoleHandler && disableConsoleHandler) {
			logger.removeHandler(handler);
		}
	}
	if (newHandler) {
		logger.addHandler(new FixedAndroidHandler());
	}
}
 
Example 58
Project: noa-libre   File: RemoteWriteTest.java   Source Code and License 6 votes vote down vote up
/**
 * Main entry point for the OpenOffice.org Remote Write Test.
 *
 * @param args arguments of the test
 *
 * @author Andreas Bröker
 * @date 17.08.2006
 */
public static void main(String[] args) {
  if(args.length < 2) {
    System.out.println("NOA Remote Write Test");
    System.out.println("-------------------");
    System.out.println("Usage:");
    System.out.println("RemoteWriteTest <host> <port>");
  }
  else { 
    LogManager.getLogManager().reset();
    ConsoleHandler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.FINEST);
    LOGGER.addHandler(consoleHandler);
    LOGGER.setLevel(Level.FINEST);
    
    try {
      FileHandler fileHandler = new FileHandler("log.xml");
      fileHandler.setLevel(Level.FINEST);
      LOGGER.addHandler(fileHandler);
    }
    catch (Throwable throwable) {
    }
    RemoteWriteTest remoteWriteTest = new RemoteWriteTest();
    remoteWriteTest.test(args[0], args[1]);
  }
}
 
Example 59
Project: RaspberryTorch   File: Logger.java   Source Code and License 6 votes vote down vote up
/**
 * INTERNAL USE ONLY! Please use the <code>Logger(String name, boolean debug)</code> contructor instead.
 * Create a new wrapper logging class with the name "RaspberryTorch". This is intended only for the internal use of the server.
 * @param debug If this logger should be in debug mode.
 */
public Logger(boolean debug){
    logger = java.util.logging.Logger.getLogger("RaspberryTorch");
    ConsoleHandler handler = new ConsoleHandler();
    if(debug){
        logger.setLevel(Level.FINE);
        handler.setLevel(Level.FINE);
    } else {
        logger.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
    }

    handler.setFormatter(new LoggerFormatter());
    logger.addHandler(handler);
}
 
Example 60
Project: RaspberryTorch   File: Logger.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new Logger with the specified <code>name</code> and debug mode.
 * @param name The name for this logger.
 * @param debug If this logger should print debug messages.
 */
public Logger(String name, boolean debug){
    logger = java.util.logging.Logger.getLogger(name);
    ConsoleHandler handler = new ConsoleHandler();
    if(debug){
        logger.setLevel(Level.FINE);
        handler.setLevel(Level.FINE);
    } else {
        logger.setLevel(Level.INFO);
        handler.setLevel(Level.INFO);
    }

    handler.setFormatter(new LoggerFormatter());
    logger.addHandler(handler);
}