Example usage for java.util.logging Handler Handler

List of usage examples for java.util.logging Handler Handler

Introduction

In this page you can find the example usage for java.util.logging Handler Handler.

Prototype

protected Handler() 

Source Link

Document

Default constructor.

Usage

From source file:Main.java

public static void main(String[] args) {
    logger.addHandler(new Handler() {
        public void publish(LogRecord logRecord) {
            strHolder.add(logRecord.getLevel() + ":");
            strHolder.add(logRecord.getSourceClassName() + ":");
            strHolder.add(logRecord.getSourceMethodName() + ":");
            strHolder.add("<" + logRecord.getMessage() + ">");
            strHolder.add("\n");
        }/*w  w  w .java  2s.c om*/

        public void flush() {
        }

        public void close() {
        }
    });
    logger.warning("Logging Warning");
    logger.info("Logging Info");
    System.out.print(strHolder);
}

From source file:org.apache.tomee.embedded.AppDataSourceTest.java

@Test
public void run() throws OpenEJBException, NamingException, IOException {
    final File tempWar = new File("target/AppDataSourceTest");
    tempWar.mkdirs();/*from   w w  w.j  a v a2 s .c  o m*/
    new File(tempWar, "WEB-INF").mkdirs();
    IO.writeString(new File(tempWar, "WEB-INF/resources.xml"),
            "<resources>\n" + "<Resource id=\"java:app/gace/MyDS\" type=\"DataSource\">\n"
                    + "DataSourceCreator=dbcp\n" + "</Resource>\n" + "</resources>\n");
    final Collection<LogRecord> records = new ArrayList<>();
    try (final Container c = new Container(new Configuration().randomHttpPort())) {
        Jdk14Logger.class.cast(LogFactory.getLog(BasicDataSource.class)).getLogger().addHandler(new Handler() {
            @Override
            public void publish(final LogRecord record) {
                if (record.getLevel() == Level.SEVERE || record.getLevel() == Level.WARNING) {
                    records.add(record);
                }
            }

            @Override
            public void flush() {
                // no-op
            }

            @Override
            public void close() throws SecurityException {
                // no-op
            }
        });
        c.deploy(null, tempWar);
    }

    // if we have the JMX bug of dbcp2 integration (in 7.0.0) then we have a WARNING record from BasicDataSource.close()
    // saying:
    // Failed to unregister the JMX name:
    //     Tomcat:type=DataSource,host=localhost,context=/AppDataSourceTest,class=javax.sql.DataSource,name="openejb/Resource/AppDataSourceTest/app/gace/MyDS"
    assertTrue(records.isEmpty());
}

From source file:org.openstreetmap.josm.data.cache.JCSCacheManager.java

@SuppressWarnings("resource")
private static void initialize() throws IOException {
    File cacheDir = new File(Main.pref.getCacheDirectory(), "jcs");

    if (!cacheDir.exists() && !cacheDir.mkdirs())
        throw new IOException("Cannot access cache directory");

    File cacheDirLockPath = new File(cacheDir, ".lock");
    if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
        LOG.log(Level.WARNING, "Cannot create cache dir lock file");
    }/*from   ww  w  .j av  a2 s .  c  o m*/
    cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();

    if (cacheDirLock == null)
        LOG.log(Level.WARNING, "Cannot lock cache directory. Will not use disk cache");

    // raising logging level gives ~500x performance gain
    // http://westsworld.dk/blog/2008/01/jcs-and-performance/
    final Logger jcsLog = Logger.getLogger("org.apache.commons.jcs");
    jcsLog.setLevel(Level.INFO);
    jcsLog.setUseParentHandlers(false);
    // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
    Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
    jcsLog.addHandler(new Handler() {
        final SimpleFormatter formatter = new SimpleFormatter();

        @Override
        public void publish(LogRecord record) {
            String msg = formatter.formatMessage(record);
            if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
                Logging.error(msg);
            } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                Logging.warn(msg);
                // downgrade INFO level to debug, as JCS is too verbose at INFO level
            } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
                Logging.debug(msg);
            } else {
                Logging.trace(msg);
            }
        }

        @Override
        public void flush() {
            // nothing to be done on flush
        }

        @Override
        public void close() {
            // nothing to be done on close
        }
    });

    // this could be moved to external file
    Properties props = new Properties();
    // these are default common to all cache regions
    // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
    // CHECKSTYLE.OFF: SingleSpaceSeparator
    props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
    props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
    props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
    props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.elementattributes.IsEternal", "false");
    props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IsSpool", "true");
    // CHECKSTYLE.ON: SingleSpaceSeparator
    CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
    cm.configure(props);
    cacheManager = cm;
}

From source file:sboulet.assignment1.BuzzerButton.java

public void makeClickable(final Context context, final BuzzerButton button) {
    //after a random time between 10 and 2000 ms
    //allow user to click on the button
    Handler handler = new Handler() {
        @Override/*from  w w w . j a v a 2  s. c  o  m*/
        public void close() {

        }

        @Override
        public void flush() {

        }

        @Override
        public void publish(LogRecord record) {

        }
    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //signal to user to click as fast as they can
            button.setRed(context);
            react.setStartTime();
            button.clickOnTime(context);
        }
    };
    buzzer.postDelayed(runnable, react.getRandomTime());
}

From source file:com.github.hronom.scrape.dat.rooms.core.grabbers.JxBrowserGrabber.java

private Handler createHandler() {
    return new Handler() {
        @Override/*  www  .  ja v  a  2 s. co m*/
        public void publish(LogRecord record) {
            if (record.getLevel() == Level.INFO) {
                logger.info(record.getMessage());
            } else if (record.getLevel() == Level.WARNING) {
                logger.warn(record.getMessage());
            } else if (record.getLevel() == Level.SEVERE) {
                logger.fatal(record.getMessage());
            } else {
                logger.info(record.getMessage());
            }
        }

        @Override
        public void flush() {

        }

        @Override
        public void close() throws SecurityException {

        }
    };
}

From source file:org.apache.shindig.gadgets.oauth.OAuthFetcherTest.java

@Before
public void setUp() throws Exception {
    base = new BasicOAuthStore();
    serviceProvider = new FakeOAuthServiceProvider(clock);
    fetcherConfig = new OAuthFetcherConfig(new BasicBlobCrypter("abcdefghijklmnop".getBytes()),
            getOAuthStore(base), new DefaultHttpCache(new LruCacheProvider(10)), clock);

    logger = Logger.getLogger(OAuthFetcher.class.getName());
    logger.addHandler(new Handler() {
        @Override//from  ww  w. jav a  2s.co m
        public void close() throws SecurityException {
        }

        @Override
        public void flush() {
        }

        @Override
        public void publish(LogRecord arg0) {
            logRecords.add(arg0);
        }
    });
}

From source file:org.apache.shindig.gadgets.oauth.OAuthRequestTest.java

@Before
public void setUp() throws Exception {
    base = new BasicOAuthStore();
    base.setDefaultCallbackUrl(GadgetTokenStoreTest.DEFAULT_CALLBACK);
    serviceProvider = new FakeOAuthServiceProvider(clock);
    callbackGenerator = createNullCallbackGenerator();
    fetcherConfig = new OAuthFetcherConfig(new BasicBlobCrypter("abcdefghijklmnop".getBytes()),
            getOAuthStore(base), clock, callbackGenerator, false);

    logger = Logger.getLogger(OAuthResponseParams.class.getName());
    logger.addHandler(new Handler() {
        @Override//from w  w w .  j av  a2s  . c om
        public void close() throws SecurityException {
        }

        @Override
        public void flush() {
        }

        @Override
        public void publish(LogRecord arg0) {
            logRecords.add(arg0);
        }
    });
}

From source file:io.trivium.Registry.java

public ArrayList<LogRecord> startBinding(TypeRef bindingTypeRef) {
    Logger logger = Logger.getLogger(bindingTypeRef.toString());
    ArrayList<LogRecord> logs = new ArrayList<>();
    Handler handler = new Handler() {
        @Override//from  w  w w.j  ava 2s.  c o m
        public void publish(LogRecord record) {
            logs.add(record);
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() throws SecurityException {
        }
    };
    logger.addHandler(handler);
    Registry.INSTANCE.getBinding(bindingTypeRef).startBinding();
    logger.removeHandler(handler);
    return logs;
}

From source file:nu.nethome.home.impl.HomeServer.java

private void setupLogger() {
    Logger.getLogger("").addHandler(new Handler() {
        @Override//  w  w  w . j av a 2s  . c o  m
        synchronized public void publish(LogRecord record) {
            newLogRecord(record);
        }

        @Override
        public void flush() {
            // Nothing to do
        }

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

From source file:brut.apktool.Main.java

private static void setupLogging(Verbosity verbosity) {
    Logger logger = Logger.getLogger("");
    for (Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);/*from  w w w . j av  a 2s.  c o  m*/
    }
    LogManager.getLogManager().reset();

    if (verbosity == Verbosity.QUIET) {
        return;
    }

    Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (getFormatter() == null) {
                setFormatter(new SimpleFormatter());
            }

            try {
                String message = getFormatter().format(record);
                if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                    System.err.write(message.getBytes());
                } else {
                    System.out.write(message.getBytes());
                }
            } catch (Exception exception) {
                reportError(null, exception, ErrorManager.FORMAT_FAILURE);
            }
        }

        @Override
        public void close() throws SecurityException {
        }

        @Override
        public void flush() {
        }
    };

    logger.addHandler(handler);

    if (verbosity == Verbosity.VERBOSE) {
        handler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
    } else {
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getLevel().toString().charAt(0) + ": " + record.getMessage()
                        + System.getProperty("line.separator");
            }
        });
    }
}