java.util.logging.Handler Java Examples

The following examples show how to use java.util.logging.Handler. 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 check out the related API usage on the sidebar.
Example #1
Source File: TwigTestBase.java    From netbeans with 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 File: LogFormatterTest.java    From netbeans with 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 #3
Source File: Client.java    From vjtools with 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 #4
Source File: FileHandlerQuerier.java    From bazel with 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 #5
Source File: LogConfigurator.java    From huaweicloud-sdk-java-obs with 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 File: JULBridge.java    From dremio-oss with 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 #7
Source File: Simulator.java    From incubator-heron with 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 #8
Source File: Logging.java    From api-mining with 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 #9
Source File: InitListener.java    From myrrix-recommender with 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 #10
Source File: AopLoggingIntegrationTest.java    From tutorials with 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
Source File: AbstractDelegatingLogger.java    From tomee with Apache License 2.0 5 votes vote down vote up
public synchronized void removeHandler(final Handler handler) throws SecurityException {
    if (supportsHandlers()) {
        super.removeHandler(handler);
        return;
    }
    throw new UnsupportedOperationException();
}
 
Example #12
Source File: LogRecords.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Scan log records from an input stream.
 * @param is the input stream to read log records from
 * @param h handler that gets the log records
 * @throws IOException when an I/O error occurs.
 */
public static void scan(InputStream is, Handler h) throws IOException {
    List<LogRecord> errorLogRecords = new ArrayList<LogRecord>();
    try {
        scan(is, h, errorLogRecords);
    } finally {
        for (LogRecord lr : errorLogRecords) {
            LOG.log(lr);
        }
    }
}
 
Example #13
Source File: TopLogging.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Initializes the logging configuration. Invoked by <code>LogManager.readConfiguration</code> method.
 */
public TopLogging() {
    AWTHandler.install();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Properties properties = System.getProperties();
    configureFromProperties(os, properties);
    try {
        StartLog.unregister();
        LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));
    } catch (IOException ex) {
        ex.printStackTrace(OLD_ERR);
    } 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 #14
Source File: VinciBinaryAnalysisEngineService_impl.java    From uima-uimaj with Apache License 2.0 5 votes vote down vote up
/**
 * Redirects all logger output for this JVM to the given output stream.
 *
 * @param out the out
 */
private static void redirectLoggerOutput(OutputStream out) {
  // get root logger handlers - root logger is parent of all loggers
  Handler[] handlers = LogManager.getLogManager().getLogger("").getHandlers();

  // remove all current handlers
  for (int i = 0; i < handlers.length; i++) {
    LogManager.getLogManager().getLogger("").removeHandler(handlers[i]);
  }

  // add new UIMAStreamHandler with the given output stream
  UIMAStreamHandler streamHandler = new UIMAStreamHandler(out, new UIMALogFormatter());
  streamHandler.setLevel(java.util.logging.Level.ALL);
  LogManager.getLogManager().getLogger("").addHandler(streamHandler);
}
 
Example #15
Source File: ConverterTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void init()
{
    final Logger root = Logger.getLogger("");
    root.setLevel(Level.ALL);
    for (Handler handler : root.getHandlers())
        handler.setLevel(root.getLevel());
}
 
Example #16
Source File: PythonProject.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
private static final void replaceAllLogFormatters(Formatter form, Level level)
/*     */   {
/* 179 */     LogManager mgr = LogManager.getLogManager();
/* 180 */     Enumeration loggerNames = mgr.getLoggerNames();
/* 181 */     while (loggerNames.hasMoreElements()) {
/* 182 */       String loggerName = (String)loggerNames.nextElement();
/* 183 */       Logger logger = mgr.getLogger(loggerName);
/* 184 */       for (Handler handler : logger.getHandlers()) {
/* 185 */         handler.setFormatter(form);
/* 186 */         handler.setLevel(level);
/*     */       }
/*     */     }
/*     */   }
 
Example #17
Source File: LogConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
public static void flushLogs() {
  Logger rootLogger = LogManager.getLogManager().getLogger("");
  if (rootLogger == null) {
    return;
  }
  Handler[] handlers = rootLogger.getHandlers();
  if (handlers == null) {
    return;
  }
  for (Handler h : handlers) {
    h.flush();
  }
}
 
Example #18
Source File: TaskProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWarningWhenRunUserTaskCalledFromAWT() throws Exception {
    this.clearWorkDir();
    final File _wd = this.getWorkDir();
    final FileObject wd = FileUtil.toFileObject(_wd);

    FileUtil.setMIMEType("foo", "text/foo");
    final FileObject foo = wd.createData("file.foo");
    final LogRecord[] warning = new LogRecord[1];
    final String msgTemplate = "ParserManager.parse called in AWT event thread by: {0}";  //NOI18N

    MockMimeLookup.setInstances(MimePath.parse("text/foo"), new FooParserFactory());
    Logger.getLogger(TaskProcessor.class.getName()).addHandler(new Handler() {
        public @Override void publish(LogRecord record) {
            if (record.getMessage().startsWith(msgTemplate)) {
                warning[0] = record;
            }
        }

        public @Override void flush() {
        }

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

    final StackTraceUserTask stackTraceUserTask = new StackTraceUserTask();
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            try {
                ParserManager.parse(Collections.singleton(Source.create(foo)), stackTraceUserTask);
            } catch (ParseException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    });

    assertNotNull("No warning when calling ParserManager.parse from AWT", warning[0]);
    assertEquals("Wrong message", msgTemplate, warning[0].getMessage());
    assertEquals("Suspiciosly wrong warning message (is the caller identified correctly?)", stackTraceUserTask.caller, warning[0].getParameters()[0]);
}
 
Example #19
Source File: DebugLogger.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example #20
Source File: FilterUtils.java    From cas-server-security-filter with Apache License 2.0 5 votes vote down vote up
public static void configureLogging(final Handler handler, final Logger logger) {
    for (final Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.setUseParentHandlers(false);

    if (handler == null) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new Formatter() {
            @Override
            public String format(final LogRecord record) {
                final StringBuffer sb = new StringBuffer();

                sb.append("[");
                sb.append(record.getLevel().getName());
                sb.append("]\t");

                sb.append(formatMessage(record));
                sb.append("\n");

                return sb.toString();
            }
        });
        logger.addHandler(consoleHandler);
    } else {
        logger.addHandler(handler);
    }

}
 
Example #21
Source File: LoggerHelper.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void deleteLoggingOnWriter() {
    Logger cxfLogger = getRootCXFLogger();
    Handler handler = getHandler(cxfLogger, WRITER_HANDLER);

    if (handler != null) {
        cxfLogger.removeHandler(handler);
    }
    enableConsoleLogging();
}
 
Example #22
Source File: ConsoleConfiguration.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
public static void initialize() {
  final ConsoleModel model =
      ConsoleModel.builder().clipboardAction(SystemClipboard::setClipboardContents).build();

  final ConsoleWindow window = new ConsoleWindow(model);
  final Handler windowHandler = new ConsoleHandler(window);

  LogManager.getLogManager().getLogger(DEFAULT_LOGGER).addHandler(windowHandler);
}
 
Example #23
Source File: AbstractDelegatingLogger.java    From openwebbeans-meecrowave with Apache License 2.0 5 votes vote down vote up
public synchronized void addHandler(Handler handler) throws SecurityException {
    if (supportsHandlers()) {
        super.addHandler(handler);
        return;
    }
    throw new UnsupportedOperationException();
}
 
Example #24
Source File: BungeeEventBus.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public void close() {
    for (Plugin plugin : this.bootstrap.getProxy().getPluginManager().getPlugins()) {
        for (Handler handler : plugin.getLogger().getHandlers()) {
            if (handler instanceof UnloadHookLoggerHandler) {
                plugin.getLogger().removeHandler(handler);
            }
        }
    }

    super.close();
}
 
Example #25
Source File: LoggingExample.java    From journaldev with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    try {
        LogManager.getLogManager().readConfiguration(new FileInputStream("mylogging.properties"));
    } catch (SecurityException | IOException e1) {
        e1.printStackTrace();
    }
    logger.setLevel(Level.FINE);
    logger.addHandler(new ConsoleHandler());
    //adding custom handler
    logger.addHandler(new MyHandler());
    try {
        //FileHandler file name with max size and number of log files limit
        Handler fileHandler = new FileHandler("/Users/pankaj/tmp/logger.log", 2000, 5);
        fileHandler.setFormatter(new MyFormatter());
        //setting custom filter for FileHandler
        fileHandler.setFilter(new MyFilter());
        logger.addHandler(fileHandler);
        
        for(int i=0; i<1000; i++){
            //logging messages
            logger.log(Level.INFO, "Msg"+i);
        }
        logger.log(Level.CONFIG, "Config data");
    } catch (SecurityException | IOException e) {
        e.printStackTrace();
    }
}
 
Example #26
Source File: LogHandler.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
public LogHandler(android.os.Handler guiHandlerCallBack){
    mHandlerCallback = guiHandlerCallBack;
    this.setLevel(Level.FINEST);
    messageBuffer = "";
    new Thread(new Runnable() {
        public void run() {
            
            while (true){
                if (messageBuffer.length() > 0){
                    long ts = System.currentTimeMillis();
                    if ((ts  - 100) > lastSendMessageTs){
                        String sendMessage = LogHandler.getMessageBuffer();
                        if (sendMessage.length() > 0){
                            Message msg = mHandlerCallback.obtainMessage(1, sendMessage);
                            mHandlerCallback.sendMessage(msg);
                            lastSendMessageTs = ts;
                        }
                    }
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
      },"LogHandler.logPumper").start();
}
 
Example #27
Source File: OpenEJBExtension.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void initLogger(final String name) {
    final Logger logger = Logger.getLogger(name);
    final Handler[] handlers = logger.getHandlers();
    if (handlers != null) {
        for (final Handler handler : handlers) {
            logger.removeHandler(handler);
        }
    }
    logger.setUseParentHandlers(false);
    logger.addHandler(new JuliLogStreamFactory.OpenEJBSimpleLayoutHandler());

}
 
Example #28
Source File: VerbatimLogger.java    From semanticvectors with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 #29
Source File: TestKit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 #30
Source File: AsqatasunCrawlJob.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Heritrix lets its log files opened at the end of the crawl.
 * We have to close them "manually".
 */
private void closeCrawlerLogFiles() {
    List<FileHandler> loggerHandlerList = new ArrayList<>();
    for (Handler handler : crawlJob.getJobLogger().getHandlers()) {
        if (handler instanceof FileHandler) {
            ((FileHandler) handler).close();
            loggerHandlerList.add((FileHandler) handler);
        }
    }
    for (FileHandler fileHandler : loggerHandlerList) {
        crawlJob.getJobLogger().removeHandler(fileHandler);
    }
}