Java Code Examples for java.util.logging.Handler.setLevel()

The following are Jave code examples for showing how to use setLevel() of the java.util.logging.Handler 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: 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 2
Project: alvisnlp   File: PlanBuilder.java   Source Code and License Vote up 6 votes
public PlanBuilder(File planDir, File resourceDir) {
	super();

	this.planDir = planDir;
	this.resourceDir = resourceDir;

	logger = Logger.getLogger(ALVISNLP_LOGGER_NAME);
	Level logLevel = Level.INFO;
	logger.setLevel(logLevel);
	logger.setUseParentHandlers(false);
   	for (Handler h : logger.getHandlers()) {
   		logger.removeHandler(h);
   	}
   	Handler stderrHandler = new FlushedStreamHandler(System.err, CommandLineLogFormatter.INSTANCE);
   	logger.addHandler(stderrHandler);
   	stderrHandler.setLevel(logLevel);
   	
       moduleFactory = new CompoundCorpusModuleFactory();
       moduleFactory.loadServiceFactories(CorpusModuleFactory.class, null, null, null);

       converterFactory = new CompoundParamConverterFactory();
       converterFactory.loadServiceFactories(ParamConverterFactory.class, null, null, null);
}
 
Example 3
Project: metanome-algorithms   File: LoggingUtils.java   Source Code and License Vote up 5 votes
public static void disableLogging() {
	// Disable Logging (FastSet sometimes complains about skewed key distributions with lots of WARNINGs)
	Logger root = Logger.getLogger("");
	Handler[] handlers = root.getHandlers();
	for (Handler handler : handlers)
		handler.setLevel(Level.OFF);
}
 
Example 4
Project: mix-them   File: MixThem.java   Source Code and License Vote up 5 votes
static void setLogging(Level level) {	
if (LOGGER.getHandlers().length == 0) {
           //System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$s] MixThem: %5$s [%1$tc]%n");            
    System.setProperty("java.util.logging.SimpleFormatter.format", "[%4$s] MixThem: %5$s%n");
    LOGGER.setUseParentHandlers(false);	 
    LOGGER.setLevel(Level.ALL);
    Handler handler = new ConsoleHandler();
    LOGGER.addHandler(handler);        
    handler.setLevel(Level.OFF);
    String prop = System.getProperty("mixthem.logging");
           if (prop == null || prop.equals("true")) {
               handler.setLevel(level);            
           }
}
   }
 
Example 5
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 6
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 7
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 8
Project: javaide   File: JavaCompiler.java   Source Code and License Vote up 5 votes
public static void enableLogging() {
    Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
    logger.setLevel(Level.ALL);
    for (Handler h : logger.getParent().getHandlers()) {
        h.setLevel(Level.ALL);
    }

}
 
Example 9
Project: bibliome-java-utils   File: BuildDictionary.java   Source Code and License Vote up 5 votes
private static Logger getLogger() {
	Logger result = Logger.getAnonymousLogger();
	result.setLevel(Level.ALL);
	result.setUseParentHandlers(false);
	Handler handler = new FlushedStreamHandler(System.err, new StandardFormatter());
	handler.setLevel(Level.ALL);
	result.addHandler(handler);
	return result;
}
 
Example 10
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 11
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 12
Project: openaudible   File: AudibleClient.java   Source Code and License Vote up 5 votes
private static void setLevel(Logger pLogger, Level pLevel) {
    Handler[] handlers = pLogger.getHandlers();
    for (Handler h : handlers) {
        h.setLevel(pLevel);
    }
    pLogger.setLevel(pLevel);
}
 
Example 13
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 14
Project: alipay-sdk   File: AlipayLogger.java   Source Code and License Vote up 5 votes
/**
 * 开启DEBUG级别日志(仅针对JDK14LOGGER,LOG4J请自行修改配置文件)
 * 
 * @param isEnabled
 */
public static void setJDKDebugEnabled(Boolean isEnabled) {
    //如果使用JDK14LOGGER,将业务日志级别设为DEBUG(FINE)
    if (blog instanceof Jdk14Logger) {
        Jdk14Logger logger = (Jdk14Logger) blog;
        if (isEnabled) {
            logger.getLogger().setLevel(Level.FINE);
            Handler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINE);
            logger.getLogger().addHandler(consoleHandler);
        } else {
            logger.getLogger().setLevel(Level.INFO);
        }
    }
}
 
Example 15
Project: pay   File: AlipayLogger.java   Source Code and License Vote up 5 votes
public static void setJDKDebugEnabled(Boolean isEnabled) {
    //如果使用JDK14LOGGER,将业务日志级别设为DEBUG(FINE)
    if (blog instanceof Jdk14Logger) {
        Jdk14Logger logger = (Jdk14Logger) blog;
        if (isEnabled) {
            logger.getLogger().setLevel(Level.FINE);
            Handler consoleHandler = new ConsoleHandler();
            consoleHandler.setLevel(Level.FINE);
            logger.getLogger().addHandler(consoleHandler);
        } else {
            logger.getLogger().setLevel(Level.INFO);
        }
    }
}
 
Example 16
Project: incubator-netbeans   File: Log.java   Source Code and License Vote up 4 votes
private Logger getPackageLogger() {
      if (logger == null) {
          String prop = System.getProperty(packageName, DEFAULT_NAME);
          for (int i = 1; i < LEVELS.length; i++) {
              if (prop.toLowerCase().equals(LEVEL_NAMES[i].toLowerCase())) {
                  level = LEVELS[i];
                  break;
              }
          }
          LogManager.getLogManager().addLogger(new Logger(packageName, null)
{});
          logger = LogManager.getLogManager().getLogger(packageName);
          if (logger == null) {
              System.out.println(packageName + ": "
		   + rb.getString("CANT_GET_LOGGER"));
              return Logger.getLogger("global");
          }
          try {
              logger.setLevel(level);
              Handler handler = new ConsoleHandler();
              handler.setLevel(level);
// Default handlers don't provide class name or method name, so roll our own
logger.setUseParentHandlers(false);
Formatter formatter = new Formatter() {
	public String format(LogRecord record) {
	    StringBuffer s = new StringBuffer();
	    s.append(record.getLevel().getLocalizedName());
	    s.append(' ');
	    if (record.getLoggerName() != null) {
		s.append('[');
		s.append(record.getLoggerName());
		s.append("]: ");
	    }
	    if (record.getSourceClassName() != null) {
		s.append("| ");
		if (record.getLevel().equals(Level.FINEST)) {
		    String className = record.getSourceClassName();
		    s.append(className.substring(Math.max(className.lastIndexOf('.')+1,0)));
		} else {
		    s.append(record.getSourceClassName());
		}
		s.append(' ');
	    }
	    if (record.getSourceMethodName() != null) {
		s.append("|  ");
		s.append(record.getSourceMethodName());
		s.append("( ");
		Object[] parms = record.getParameters();
		if (parms != null) {
		    for (int i = 0; i < parms.length; i++) {
			if (i != 0) {
			    s.append(", ");
			}
			s.append(parms[i]);
		    }
		}
		s.append(" ) ");
	    }
	    if (record.getThrown() != null) {
		s.append("| ");
		s.append(record.getThrown());
	    }
	    if (record.getMessage() != null) {
		s.append('|');
		s.append(record.getMessage());
	    }
	    s.append('\n');
	    return s.toString();
	}
                  };
              handler.setFormatter(formatter);
              logger.addHandler(handler);
          }
          catch (SecurityException e) {
          }
      }

      return logger;
  }
 
Example 17
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);
  }
}