Example usage for java.util.logging StreamHandler StreamHandler

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

Introduction

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

Prototype

public StreamHandler(OutputStream out, Formatter formatter) 

Source Link

Document

Create a StreamHandler with a given Formatter and output stream.

Usage

From source file:android.net.http.CookiesTest.java

/**
 * Test that we don't log potentially sensitive cookie values.
 * http://b/3095990//  w w w  .j a  v  a 2  s.  c  o  m
 */
public void testCookiesAreNotLogged() throws IOException, URISyntaxException {
    // enqueue an HTTP response with a cookie that will be rejected
    server.enqueue(new MockResponse().addHeader("Set-Cookie: password=secret; Domain=fake.domain"));
    server.play();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Logger logger = Logger.getLogger("org.apache.http");
    StreamHandler handler = new StreamHandler(out, new SimpleFormatter());
    logger.addHandler(handler);
    try {
        HttpClient client = new DefaultHttpClient();
        client.execute(new HttpGet(server.getUrl("/").toURI()));
        handler.close();

        String log = out.toString("UTF-8");
        assertTrue(log, log.contains("password"));
        assertTrue(log, log.contains("fake.domain"));
        assertFalse(log, log.contains("secret"));

    } finally {
        logger.removeHandler(handler);
    }
}

From source file:cn.org.once.cstack.cli.processor.LoggerPostProcessor.java

public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            if (field.getAnnotation(InjectLogger.class) != null && field.getType().equals(Logger.class)) {
                ReflectionUtils.makeAccessible(field);
                Logger logger = Logger.getLogger(bean.getClass().getName());

                field.set(bean, logger);

                StreamHandler fileHandler;
                try {

                    FileOutputStream fileOutputStream = new FileOutputStream(new File("errors.log"), true);
                    fileHandler = new StreamHandler(fileOutputStream, new SimpleFormatter());
                    fileHandler.setLevel(Level.SEVERE);
                    logger.addHandler(fileHandler);

                } catch (SecurityException | IOException e) {
                    throw new IllegalArgumentException(e);
                }/*  w  w w  .  ja  va 2  s .c  o m*/

            }
        }
    });

    return bean;
}

From source file:net.poemerchant.ui.ScraperSwingWorker.java

@Override
public Void doInBackground() throws Exception {
    // all logger message will also go to our printStream 
    logger.addHandler(new StreamHandler(printStream, new Formatter() {

        @Override/*from  w w  w .ja  v a  2  s.c  o m*/
        public String format(LogRecord record) {
            //            System.out.println("intercept: " + record.getMessage());
            return record.getMessage() + System.lineSeparator();
        }
    }) {
        @Override
        public synchronized void publish(LogRecord record) {
            super.publish(record);
            flush();
        }
    });

    ShopIndexScraper scraper = new ShopIndexScraper(shopSubForumUrl);

    logger.info("Scrapping shops subform index: " + shopSubForumUrl);

    List<String> shopUrls = null;
    try {
        shopUrls = scraper.scrape();
    } catch (PoEMerchantException e) {
        logger.severe("Error: " + e.getMessage() + ". Try again.");
        return null;
    }

    //      shopUrls = new ArrayList();
    //      shopUrls.add(this.getClass().getResource("/1148541.htm").getFile());
    logger.info("Sucessfully scraped subform, number of shops: " + shopUrls.size());

    for (String url : shopUrls) {
        logger.info("Scrapping shop: " + url);
        try {
            scrapeAndSaveShop(configuration.getIndex(), configuration.getType(), url);
        } catch (Exception e) {
            logger.severe("error caught for " + url + ". err msg: " + e.getMessage());
        }
    }

    logger.info(String.format("Sucessfully scraped %d shops.", shopUrls.size()));

    return null;
}

From source file:com.bc.fiduceo.post.PostProcessingToolTest.java

@Test
public void testThatPostProcessingToolInCaseOfExceptionsPrintsTheErrorMessageAndContinueWithTheNextFile()
        throws Exception {
    final ArrayList<Path> mmdFiles = new ArrayList<>();
    mmdFiles.add(Paths.get("nonExistingFileOne"));
    mmdFiles.add(Paths.get("nonExistingFileTwo"));
    mmdFiles.add(Paths.get("nonExistingFileThree"));

    final Formatter formatter = new SimpleFormatter();
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final StreamHandler handler = new StreamHandler(stream, formatter);
    final Logger logger = FiduceoLogger.getLogger();
    FiduceoLogger.setLevelSilent();/*w w  w  .j  av a2s  .  com*/

    try {
        logger.addHandler(handler);

        final PostProcessingContext context = new PostProcessingContext();
        final PostProcessingConfig processingConfig = getConfig();
        context.setProcessingConfig(processingConfig);

        final PostProcessingTool postProcessingTool = new PostProcessingTool(context);

        postProcessingTool.computeFiles(mmdFiles);

        handler.close();
        final String string = stream.toString();
        assertThat(string, CoreMatchers.containsString("nonExistingFileOne"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileTwo"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileThree"));
    } finally {
        logger.removeHandler(handler);
    }
}

From source file:net.sourceforge.pmd.junit.JavaUtilLoggingRule.java

/**
 * Creates a new rule, that attaches a custom log handler
 * to the given logger.//  w  w  w .j a v a 2  s .c o m
 * @param loggerName the name of the logger to check
 */
public JavaUtilLoggingRule(String loggerName) {
    this.logger = Logger.getLogger(loggerName);
    this.stream = new ByteArrayOutputStream();

    Logger currentLogger = logger;
    while (currentLogger.getHandlers().length == 0) {
        currentLogger = currentLogger.getParent();
    }
    this.customLogHandler = new StreamHandler(stream, currentLogger.getHandlers()[0].getFormatter());
}