Java Code Examples for java.util.logging.Handler

The following examples show how to use java.util.logging.Handler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: netbeans   Source File: TwigTestBase.java    License: Apache License 2.0 6 votes vote down vote up
private static void suppressUselessLogging() {
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setFilter(new Filter() {

            @Override
            public boolean isLoggable(LogRecord record) {
                boolean result = true;
                if (record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.LogContext")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.parsing.impl.indexing.RepositoryUpdater")
                        || record.getSourceClassName().startsWith("org.netbeans.modules.editor.settings.storage.keybindings.KeyMapsStorage")) { //NOI18N
                    result = false;
                }
                return result;
            }
        });
    }
}
 
Example 2
Source Project: myrrix-recommender   Source File: InitListener.java    License: Apache License 2.0 6 votes vote down vote up
private static void configureLogging(ServletContext context) {
  MemoryHandler.setSensibleLogFormat();
  Handler logHandler = null;
  for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
    if (handler instanceof MemoryHandler) {
      logHandler = handler;
      break;
    }
  }
  if (logHandler == null) {
    // Not previously configured by command line, make a new one
    logHandler = new MemoryHandler();
    java.util.logging.Logger.getLogger("").addHandler(logHandler);
  }
  context.setAttribute(LOG_HANDLER, logHandler);
}
 
Example 3
Source Project: netbeans   Source File: LogFormatterTest.java    License: Apache License 2.0 6 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 4
Source Project: dremio-oss   Source File: JULBridge.java    License: Apache License 2.0 6 votes vote down vote up
public static void configure() {
  // Route JUL logging messages to SLF4J.
  LogManager.getLogManager().reset();
  SLF4JBridgeHandler.removeHandlersForRootLogger();
  SLF4JBridgeHandler.install();

  // Parquet installs a default handler if none found, so remove existing handlers and add slf4j
  // one.
  // Also add slf4j bridge handle and configure additivity to false so that log messages are not
  // printed out twice
  final Handler[] handlers = PARQUET_ROOT_LOGGER.getHandlers();
  for(int i = 0; i < handlers.length; i++) {
    PARQUET_ROOT_LOGGER.removeHandler(handlers[i]);
  }
  PARQUET_ROOT_LOGGER.addHandler(new SLF4JBridgeHandler());
  PARQUET_ROOT_LOGGER.setUseParentHandlers(false);
}
 
Example 5
Source Project: huaweicloud-sdk-java-obs   Source File: LogConfigurator.java    License: Apache License 2.0 6 votes vote down vote up
private static void logOff(Logger pLogger)
{
    pLogger.setLevel(LogConfigurator.OFF);
    Handler[] handlers = pLogger.getHandlers();
    if(handlers != null){
        for(Handler handler : handlers){
            pLogger.removeHandler(handler);
        }
    }
    if(pLogger == accessLogger)
    {
        accessLogEnabled = false;
    }
    else if(pLogger == logger)
    {
        logEnabled = false;
    }
}
 
Example 6
Source Project: bazel   Source File: FileHandlerQuerier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Optional<Path> getLogHandlerFilePath(Handler handler) {
  // Hack: java.util.logging.FileHandler has no API for getting the current file path. Instead, we
  // try to parse the configured path and check that it has no % variables.
  String pattern = logManagerSupplier.get().getProperty("java.util.logging.FileHandler.pattern");
  if (pattern == null) {
    throw new IllegalStateException(
        "java.util.logging.config property java.util.logging.FileHandler.pattern is undefined");
  }
  if (pattern.matches(".*%[thgu].*")) {
    throw new IllegalStateException(
        "resolving %-coded variables in java.util.logging.config property "
            + "java.util.logging.FileHandler.pattern is not supported");
  }
  Path path = Paths.get(pattern.trim());

  // Hack: java.util.logging.FileHandler has no API for checking if a log file is currently open.
  // Instead, we try to query whether the handler can log a SEVERE level record - which for
  // expected configurations should be true iff a log file is open.
  if (!handler.isLoggable(new LogRecord(Level.SEVERE, ""))) {
    return Optional.empty();
  }
  return Optional.of(path);
}
 
Example 7
Source Project: vjtools   Source File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	Client client = new Client();
	// Set the logger to use our all-on-one-line formatter.
	Logger l = Logger.getLogger("");
	Handler[] hs = l.getHandlers();
	for (int i = 0; i < hs.length; i++) {
		Handler h = hs[0];
		if (h instanceof ConsoleHandler) {
			h.setFormatter(client.new OneLineSimpleLogger());
		}
	}
	try {
		client.execute(args);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 8
Source Project: incubator-heron   Source File: Simulator.java    License: Apache License 2.0 6 votes vote down vote up
private void handleException(Thread thread, Throwable exception) {
  LOG.severe("Local Mode Process exiting.");
  LOG.log(Level.SEVERE,
      "Exception caught in thread: " + thread.getName() + " with id: " + thread.getId(),
      exception);
  for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
    handler.close();
  }

  // Attempts to shutdown all the thread in threadsPool. This will send Interrupt to every
  // thread in the pool. Threads may implement a clean Interrupt logic.
  threadsPool.shutdownNow();

  // not owned by HeronInstance). To be safe, not sending these interrupts.
  Runtime.getRuntime().halt(1);
}
 
Example 9
Source Project: api-mining   Source File: Logging.java    License: GNU General Public License v3.0 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 10
Source Project: tutorials   Source File: AopLoggingIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
    messages = new ArrayList<>();

    logEventHandler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            messages.add(record.getMessage());
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };

    Logger logger = Logger.getLogger(LoggingAspect.class.getName());
    logger.addHandler(logEventHandler);
}
 
Example 11
private static VerbatimLogger getVerbatimLogger() {
  if (singletonLogger == null) {
    singletonLogger = new VerbatimLogger();
    ConsoleHandler cs = new ConsoleHandler();
    singletonFormatter = singletonLogger.new VerbatimFormatter();
    cs.setFormatter(singletonFormatter);
    VerbatimLogger.underlyingLogger = Logger.getLogger("VerbatimLogger");
    VerbatimLogger.underlyingLogger.setUseParentHandlers(false);
    for (Handler handler : underlyingLogger.getHandlers()) {
      underlyingLogger.removeHandler(handler);
    }
    underlyingLogger.addHandler(cs);
  }
  return singletonLogger;
}
 
Example 12
Source Project: netbeans   Source File: ExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test GlassFishException with message and cause <code>Throwable</code>
 * throwing and logging.
 */
@Test
public void testGlassFishExceptionWithMsgAndCause() {
    String gfieMsg = "Test exception";
    String causeMsg = "Cause exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        try {
            throw new Exception(causeMsg);
        } catch (Exception e) {
            throw new GlassFishIdeException(gfieMsg, e);
        }
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int containsGfieMsg = logMsg.indexOf(gfieMsg);
    int containsCauseMsg = logMsg.indexOf(causeMsg);
    assertTrue(containsGfieMsg > -1 && containsCauseMsg > -1);
}
 
Example 13
Source Project: grpc-nebula-java   Source File: ContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void detachingNonCurrentLogsSevereMessage() {
  final AtomicReference<LogRecord> logRef = new AtomicReference<LogRecord>();
  Handler handler = new Handler() {
    @Override
    public void publish(LogRecord record) {
      logRef.set(record);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
  };
  Logger logger = Logger.getLogger(Context.storage().getClass().getName());
  try {
    logger.addHandler(handler);
    Context initial = Context.current();
    Context base = initial.withValue(PET, "dog");
    // Base is not attached
    base.detach(initial);
    assertSame(initial, Context.current());
    assertNotNull(logRef.get());
    assertEquals(Level.SEVERE, logRef.get().getLevel());
  } finally {
    logger.removeHandler(handler);
  }
}
 
Example 14
Source Project: grpc-nebula-java   Source File: ContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  Logger logger = Logger.getLogger(Context.class.getName());
  logger.setLevel(Level.ALL);
  Handler handler = new Handler() {
    @Override
    public void publish(LogRecord record) {
      Context ctx = Context.current();
      Context previous = ctx.attach();
      ctx.detach(previous);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
  };
  logger.addHandler(handler);

  try {
    assertNotNull(Context.ROOT);
  } finally {
    logger.removeHandler(handler);
  }
}
 
Example 15
Source Project: Open-Lowcode   Source File: OLcServer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static void main(String args[]) {
	if (args.length != 1) {
		System.err.println("Error : syntax java OLcServer configfilepath");
		System.err.println("   Where configfilepath is a valid path to an Open Lowcode server");
		System.err.println("         configuration file");
	}

	Runtime.getRuntime().addShutdownHook(new Thread() {
		public void run() {
			System.err.println("starting shutdown sequence");
			try {

				PersistenceGateway.getStorage().closeConnections();

			} catch (RuntimeException e) {
				System.err.println("Error during exit connection close " + e.getMessage());
			}
			Logger logger = Logger.getLogger("");
			Handler[] handler = logger.getHandlers();
			for (int i = 0; i < handler.length; i++) {
				handler[i].close();
				logger.removeHandler(handler[i]);

			}
			System.err.println("logger closed. shutting down gracefully");
		}
	});

	serversingleton = new OLcServer(args[0]);
}
 
Example 16
Source Project: nadia   Source File: NadiaProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void init(){
	init=true;
	startedOn = new Date();
	//format logging
	logger.setUseParentHandlers(false);	 
	CustomFormatter fmt = new CustomFormatter();
	Handler ch = new ConsoleHandler();
	ch.setFormatter(fmt);
	logger.addHandler(ch);
	
	logger.setLevel(Level.INFO);
}
 
Example 17
Source Project: api-mining   Source File: Logging.java    License: GNU General Public License v3.0 5 votes vote down vote up
/** Set up logging to file */
public static void setUpFileLogger(final Logger logger, final Level logLevel, final File logFile) {
	LogManager.getLogManager().reset();
	logger.setLevel(logLevel);
	final Handler handler = setUpFileHandler(logFile.getAbsolutePath());
	logger.addHandler(handler);
}
 
Example 18
Source Project: LicenseScout   Source File: BaseFinderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Initializes logging.
 * @throws Exception
 */
@BeforeClass
public static void setUpClass() throws Exception {
    Logger.getGlobal().setLevel(Level.FINEST);
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.FINEST);
    Logger.getGlobal().addHandler(consoleHandler);
    TestUtil.setDefaultMessageDigestAlgorithm();
}
 
Example 19
Source Project: opentelemetry-java   Source File: LoggingMetricExporter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Flushes the data.
 *
 * @return the result of the operation
 */
@Override
public ResultCode flush() {
  ResultCode resultCode = ResultCode.SUCCESS;
  for (Handler handler : logger.getHandlers()) {
    try {
      handler.flush();
    } catch (Throwable t) {
      resultCode = ResultCode.FAILURE;
    }
  }
  return resultCode;
}
 
Example 20
Source Project: gemfirexd-oss   Source File: LogWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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 21
/**
 * Finishes the process and cleans up everything, including GUI.
 *
 * @since 7.4
 */
private void finishProcess(Handler logHandler) {
	stop();
	tearDown();
	if (logHandler != null) {
		getLogger().removeHandler(logHandler);
		logHandler.close();
	}
	ActionStatisticsCollector.getInstance().logExecutionFinished(this);
}
 
Example 22
Source Project: gcp-token-broker   Source File: BrokerServer.java    License: Apache License 2.0 5 votes vote down vote up
private static void setLoggingLevel() {
    Level level = Level.parse(AppSettings.getInstance().getString(AppSettings.LOGGING_LEVEL));
    Logger root = Logger.getLogger("");
    root.setLevel(level);
    for (Handler handler : root.getHandlers()) {
        handler.setLevel(level);
    }
}
 
Example 23
Source Project: tomee   Source File: LoggerCreator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Logger call() throws Exception {
    if (logger == null) {
        synchronized (this) { // no need of lock for this part
            if (logger == null) {
                final Thread thread = Thread.currentThread();
                final ClassLoader originalLoader = thread.getContextClassLoader();
                thread.setContextClassLoader(ParentClassLoaderFinder.Helper.get());
                try {
                    try {
                        logger = Logger.getLogger(name);
                    } catch (final Exception e) {
                        logger = Logger.getLogger(name); // try again
                    }

                    // if level set through properties force it
                    final Properties p = SystemInstance.get().getProperties();
                    final String levelName = p.getProperty("logging.level." + logger.getName());
                    if (levelName != null) {
                        final Level level = Level.parse(levelName);
                        for (final Handler handler : logger.getHandlers()) {
                            handler.setLevel(level);
                        }
                    }
                } finally {
                    thread.setContextClassLoader(originalLoader);
                }
            }
        }
    }
    return logger;
}
 
Example 24
Source Project: cxf   Source File: AbstractDelegatingLogger.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void removeHandler(Handler handler) {
    if (supportsHandlers()) {
        super.removeHandler(handler);
        return;
    }
    throw new UnsupportedOperationException();
}
 
Example 25
Source Project: android-uiconductor   Source File: UicdCLI.java    License: Apache License 2.0 5 votes vote down vote up
private static void setRedirectOutputToFile(Path logFolder) throws IOException {
  Path logFilePath =
      Paths.get(logFolder.toString(), LOG_FILENAME_PREFIX + new Date().getTime() + ".txt");
  System.out.println("Starting print to file...\n" + logFilePath.toString());
  Handler fh = new FileHandler(logFilePath.toString());
  fh.setFormatter(new SimpleFormatter());

  // Remove the output in the console.
  LogManager.getLogManager().reset();
  Logger.getLogger("uicd").addHandler(fh);
}
 
Example 26
Source Project: jatecs   Source File: ExecutionLogger.java    License: GNU General Public License v3.0 5 votes vote down vote up
public ExecutionLogger() {
    super(ExecutionLogger.class.getName(), null);

    Handler h = new ConsoleHandler();
    h.setFormatter(new StatusOutputFormatter());
    addHandler(h);
    setUseParentHandlers(false);
    setLevel(Level.INFO);
}
 
Example 27
Source Project: netbeans   Source File: FileUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
/** Test recovery of FileUtil.createFolder(FileObject, String) method when
 * other thread created folder in the middle of processing (see #152219).
 */
public void testFolderAlreadyExists152219() {
    final FileObject folder = FileUtil.createMemoryFileSystem().getRoot();
    final String name = "subfolder";
    Handler handler = new Handler() {

        @Override
        public void publish(LogRecord record) {
            if (record.getMessage().equals("createFolder - before create folder if not exists.")) {
                try {
                    folder.createFolder(name);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    Logger logger = Logger.getLogger(FileUtil.class.getName());
    logger.addHandler(handler);
    logger.setLevel(Level.FINEST);
    try {
        FileUtil.createFolder(folder, name);
    } catch (IOException ioe) {
        fail("FileUtil.createFolder(FileObject, String) should try to refresh folder because other thread can create folder before.");
    } finally {
        logger.removeHandler(handler);
    }
}
 
Example 28
Source Project: jatecs   Source File: ExecutionLogger.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void print(String msg) {
    info(msg);
    _logger.info(msg);

    Handler handlers[] = getHandlers();
    for (int i = 0; i < handlers.length; i++)
        handlers[i].flush();
}
 
Example 29
Source Project: tomee   Source File: Log4jLogger.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized Handler[] getHandlers() {
    final List<Handler> ret = new ArrayList<>();
    final Enumeration<?> en = log.getAllAppenders();
    while (en.hasMoreElements()) {
        final Appender ap = (Appender) en.nextElement();
        if (ap instanceof HandlerWrapper) {
            ret.add(((HandlerWrapper) ap).getHandler());
        }
    }
    return ret.toArray(new Handler[ret.size()]);
}
 
Example 30
Source Project: grpc-java   Source File: ContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void detachingNonCurrentLogsSevereMessage() {
  final AtomicReference<LogRecord> logRef = new AtomicReference<>();
  Handler handler = new Handler() {
    @Override
    public void publish(LogRecord record) {
      logRef.set(record);
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
    }
  };
  Logger logger = Logger.getLogger(Context.storage().getClass().getName());
  try {
    logger.addHandler(handler);
    Context initial = Context.current();
    Context base = initial.withValue(PET, "dog");
    // Base is not attached
    base.detach(initial);
    assertSame(initial, Context.current());
    assertNotNull(logRef.get());
    assertEquals(Level.SEVERE, logRef.get().getLevel());
  } finally {
    logger.removeHandler(handler);
  }
}