Java Code Examples for java.util.logging.Logger.getHandlers()

The following are Jave code examples for showing how to use getHandlers() of the java.util.logging.Logger class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: scorekeeperfrontend   File: AppSetup.java   Source Code and License Vote up 8 votes
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 2
Project: Pogamut3   File: SimpleLogging.java   Source Code and License Vote up 6 votes
public static void initLogging(boolean time) {
	
	Logger log = Logger.getAnonymousLogger();
	while (log != null) {
		for (Handler handler : log.getHandlers()) {
			log.removeHandler(handler);
		}
		if (log.getParent() == null) {
			if (time) {
				log.addHandler(new TimeLogHandler());
			} else {
				log.addHandler(new SimpleLogHandler());
			}
		}
		log = log.getParent();
	}		
}
 
Example 3
Project: alvisnlp   File: AbstractAlvisNLP.java   Source Code and License Vote up 6 votes
private void setHandlers(Logger logger, File file) throws FileNotFoundException {
  	for (Handler h : logger.getHandlers()) {
  		logger.removeHandler(h);
  	}
      Handler stderrHandler = new FlushedStreamHandler(System.err, noColors ? CommandLineLogFormatter.INSTANCE : CommandLineLogFormatter.COLORS);
      logger.addHandler(stderrHandler);
      if (file == null)
	stderrHandler.setLevel(logLevel);
else {
	File dir = file.getParentFile();
	if (dir != null) {
		dir.mkdirs();
	}
          Handler fileHandler = new FlushedStreamHandler(new FileOutputStream(file, appendToLog), CommandLineLogFormatter.INSTANCE);
          logger.addHandler(fileHandler);
          if (logLevel.intValue() < Level.FINE.intValue()) {
              fileHandler.setLevel(logLevel);
              stderrHandler.setLevel(Level.FINE);
          }
          else {
              fileHandler.setLevel(Level.FINE);
              stderrHandler.setLevel(logLevel);
          }
      }
  }
 
Example 4
Project: Example.EMA.Java.SpeedGuide   File: SpeedGuideConsumer.java   Source Code and License Vote up 6 votes
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 5
Project: scorekeeperfrontend   File: AppSetup.java   Source Code and License Vote up 6 votes
/**
 * 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 6
Project: incubator-netbeans   File: TestKit.java   Source Code and License Vote up 5 votes
public static void removeHandlers(Logger log) {
    if (log != null) {
        Handler[] handlers = log.getHandlers();
        for (int i = 0; i < handlers.length; i++) {
            log.removeHandler(handlers[i]);
        }
    }
}
 
Example 7
Project: incubator-netbeans   File: AutoSubmitTest.java   Source Code and License Vote up 5 votes
private static boolean checkHandlers(String msg, Logger logger) {
    Handler[] handlers = logger.getHandlers();
    int n = 0;
    for (Handler h : handlers) {
        if (h instanceof UIHandler && !((UIHandler) h).isExceptionOnly()) {
            n++;
        }
    }
    System.err.println(msg+" Handlers with not exception only = "+n+", logger = "+logger);
    return n == 1;
}
 
Example 8
Project: monarch   File: LogWrapper.java   Source Code and License Vote up 5 votes
/**
 * Removed all the handlers of the given {@link Logger} instance.
 *
 * @param logger {@link Logger} to be cleaned up.
 */
private static void cleanupLogger(Logger logger) {
  if (logger != null) {
    Handler[] handlers = logger.getHandlers();
    for (Handler handler : handlers) {
      handler.close();
      logger.removeHandler(handler);
    }
  }
}
 
Example 9
Project: gw2_launcher   File: Operations.java   Source Code and License Vote up 5 votes
public static void closeLogHandlers(Logger log) {
	if (DEBUG) {
		for (Handler e: log.getHandlers()) {
			e.close();
		}
	}
}
 
Example 10
Project: alog   File: Alog.java   Source Code and License Vote up 5 votes
/**
 * Adds a FileLogHandler to the named logger, if there isn't one already.
 * This can be used repeatedly to acquire the same logger, but doing so would be
 * inefficient.  Use Logger.getLogger after this has installed the handler.
 *
 * @param name Log name.
 * @param logFile Where record the log, may be null.  Multiple logs can safely share the same
 * file.
 */
public static Logger getLogger(String name, File logFile) {
    Logger ret = Logger.getLogger(name);
    FileLogHandler fileLogHandler = FileLogHandler.getHandler(logFile);
    for (Handler handler : ret.getHandlers()) {
        if (handler == fileLogHandler) {
            return ret;
        }
    }
    ret.addHandler(fileLogHandler);
    return ret;
}
 
Example 11
Project: lokalized-java   File: LoggingUtils.java   Source Code and License Vote up 5 votes
/**
 * Overrides the system's root logger level.
 * <p>
 * This is for internal testing and debugging only!
 *
 * @param level the level to use, not null
 */
@Nonnull
public static void setRootLoggerLevel(@Nonnull Level level) {
  Objects.requireNonNull(level);

  Logger rootLogger = Logger.getLogger("");

  for (Handler handler : rootLogger.getHandlers())
    handler.setLevel(Level.FINEST);

  rootLogger.setLevel(level);
}
 
Example 12
Project: alog   File: Alog.java   Source Code and License Vote up 5 votes
/**
 * Removes existing handlers from the root logger and installs a
 * PrintStreamLogHandler for System.out.
 */
public static void replaceRootHandler() {
    Logger global = Logger.getLogger("");
    for (Handler handler : global.getHandlers()) {
        global.removeHandler(handler);
    }
    global.addHandler(new PrintStreamLogHandler("Root Logger", System.out));
}
 
Example 13
Project: alog   File: Alog.java   Source Code and License Vote up 5 votes
/**
 * Removes existing handlers from the root logger and installs a
 * FileLogHandler.
 */
public static void replaceRootHandler(File logFile) {
    Logger global = Logger.getLogger("");
    for (Handler handler : global.getHandlers()) {
        global.removeHandler(handler);
    }
    FileLogHandler fileLogHandler = FileLogHandler.getHandler(logFile);
    global.addHandler(fileLogHandler);
}
 
Example 14
Project: item-shop-reactive-backend   File: ApplicationListenerBean.java   Source Code and License Vote up 5 votes
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent) {
		Logger log = LogManager.getLogManager().getLogger("");
		for (Handler h : log.getHandlers()) {
		    h.setLevel(Level.INFO);
		}        	
    }
}
 
Example 15
Project: Java-EX   File: LogUtil.java   Source Code and License Vote up 5 votes
public static void setGlobalLevel(Level newLevel) {
  Logger rootLogger = LogManager.getLogManager().getLogger("");
  rootLogger.setLevel(newLevel);
  for (Handler h : rootLogger.getHandlers()) {
    h.setLevel(newLevel);
  }
}
 
Example 16
Project: alvisnlp   File: Run.java   Source Code and License Vote up 5 votes
public void setHandlers(Logger logger, Level logLevel) throws FileNotFoundException {
	for (Handler h : logger.getHandlers()) {
		logger.removeHandler(h);
	}
	Handler stderrHandler = new FlushedStreamHandler(System.err, CommandLineLogFormatter.INSTANCE);
	logger.addHandler(stderrHandler);
	stderrHandler.setLevel(logLevel);

	Handler fileHandler = new FlushedStreamHandler(new FileOutputStream(new File(processingDir, ALVISNLP_LOG_FILENAME), false), CommandLineLogFormatter.INSTANCE);
    logger.addHandler(fileHandler);
	fileHandler.setLevel(logLevel);
}
 
Example 17
Project: shuffleboard   File: Shuffleboard.java   Source Code and License Vote up 5 votes
/**
 * Sets up loggers to print to stdout (rather than stderr) and log to ~/Shuffleboard/shuffleboard.log
 */
private void setupLoggers() throws IOException {
  //Set up the global level logger. This handles IO for all loggers.
  final Logger globalLogger = LogManager.getLogManager().getLogger("");

  // Remove the default handlers that stream to System.err
  for (Handler handler : globalLogger.getHandlers()) {
    globalLogger.removeHandler(handler);
  }

  final Handler fileHandler = new FileHandler(Storage.getStorageDir() + "/shuffleboard.log");

  fileHandler.setLevel(Level.INFO);    // Only log INFO and above to disk
  globalLogger.setLevel(Level.CONFIG); // Log CONFIG and higher

  // We need to stream to System.out instead of System.err
  final StreamHandler sh = new StreamHandler(System.out, new SimpleFormatter()) {
    @Override
    public synchronized void publish(final LogRecord record) { // NOPMD this is the same signature as the superclass
      super.publish(record);
      // For some reason this doesn't happen automatically.
      // This will ensure we get all of the logs printed to the console immediately instead of at shutdown
      flush();
    }
  };
  sh.setLevel(Level.CONFIG); // Log CONFIG and higher to stdout

  globalLogger.addHandler(sh);
  globalLogger.addHandler(fileHandler);
  fileHandler.setFormatter(new SimpleFormatter()); //log in text, not xml

  globalLogger.config("Configuration done."); //Log that we are done setting up the logger
  globalLogger.config("Shuffleboard app version: " + Shuffleboard.class.getPackage().getImplementationVersion());
}
 
Example 18
Project: openjdk-jdk10   File: TestInferCaller.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    TestInferCaller test = new TestInferCaller();
    Logger root = Logger.getLogger("");
    for (Handler h : root.getHandlers()) {
        h.setLevel(Level.OFF);
    }
    root.addHandler(new TestHandler());

    for (Logger logger : Arrays.asList(root, Logger.getGlobal(),
            Logger.getAnonymousLogger(), Logger.getLogger("foo.bar"))) {
        System.out.println("Testing with: " + loggerName(logger) + " " + logger.getClass());
        test.test(logger);
    }
}
 
Example 19
Project: incubator-netbeans   File: TopLogging.java   Source Code and License Vote up 4 votes
/** Initializes the logging configuration. Invoked by <code>LogManager.readConfiguration</code> method.
 */
public TopLogging() {
    AWTHandler.install();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(os);

    Collection<Logger> keep = new LinkedList<Logger>();
    Properties properties = System.getProperties();
    for (String key : properties.stringPropertyNames()) {
        
        if ("sun.os.patch.level".equals(key)) { // NOI18N
            // skip this property as it does not mean level of logging
            continue;
        }

        String v = properties.getProperty(key);
        if (v == null) {
            continue;
        }

        if (key.endsWith(".level")) {
            ps.print(key);
            ps.print('=');
            ps.println(v);
            keep.add(Logger.getLogger(key.substring(0, key.length() - 6)));
        }
    }
    ps.close();
    try {
        StartLog.unregister();
        LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        StartLog.register();
    }


    Logger logger = Logger.getLogger (""); // NOI18N

    Handler[] old = logger.getHandlers();
    for (int i = 0; i < old.length; i++) {
        logger.removeHandler(old[i]);
    }
    logger.addHandler(defaultHandler ());
    if (!disabledConsole) { // NOI18N
        logger.addHandler (streamHandler ());
    }
    logger.addHandler(new LookupDel());
}
 
Example 20
Project: java-monitoring-client-library   File: SheepCounterExample.java   Source Code and License Vote up 4 votes
public static void main(String[] args) throws Exception {
  if (args.length < 1) {
    System.err.println("Missing required project argument");
    System.err.printf(
        "Usage: java %s gcp-project-id [verbose]\n", SheepCounterExample.class.getName());
    return;
  }
  String project = args[0];

  // Turn up the logging verbosity
  if (args.length > 1) {
    Logger log = LogManager.getLogManager().getLogger("");
    log.setLevel(Level.ALL);
    for (Handler h : log.getHandlers()) {
      h.setLevel(Level.ALL);
    }
  }

  // Create a sample resource. In this case, a GCE Instance.
  // See https://cloud.google.com/monitoring/api/resources for a list of resource types.
  MonitoredResource monitoredResource =
      new MonitoredResource()
          .setType("gce_instance")
          .setLabels(
              ImmutableMap.of(
                  "instance_id", "test-instance",
                  "zone", "us-central1-f"));

  // Set up the Metrics infrastructure.
  MetricWriter stackdriverWriter =
      new StackdriverWriter(
          createAuthorizedMonitoringClient(),
          project,
          monitoredResource,
          STACKDRIVER_MAX_QPS,
          STACKDRIVER_MAX_POINTS_PER_REQUEST);
  final MetricReporter reporter =
      new MetricReporter(
          stackdriverWriter, METRICS_REPORTING_INTERVAL, Executors.defaultThreadFactory());
  reporter.startAsync().awaitRunning();

  // Set up a handler to stop sleeping on SIGINT.
  Runtime.getRuntime()
      .addShutdownHook(
          new Thread(
              () -> {
                reporter.stopAsync().awaitTerminated();
                // Allow the LogManager to cleanup the loggers.
                DelayedShutdownLogManager.resetFinally();
              }));

  System.err.println("Send SIGINT (Ctrl+C) to stop sleeping.");
  while (true) {
    // Count some Googley sheep.
    int colorIndex = new Random().nextInt(SHEEP_COLORS.size());
    int speciesIndex = new Random().nextInt(SHEEP_SPECIES.size());
    sheepCounter.incrementBy(1, SHEEP_COLORS.get(colorIndex), SHEEP_SPECIES.get(speciesIndex));
    sheepFluffiness.record(
        new Random().nextDouble() * 200,
        SHEEP_COLORS.get(colorIndex),
        SHEEP_SPECIES.get(speciesIndex));
    isSleeping.set(true);

    logger.info("zzz...");
    Thread.sleep(5000);
  }
}