Example usage for java.util.logging Logger addHandler

List of usage examples for java.util.logging Logger addHandler

Introduction

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

Prototype

public void addHandler(Handler handler) throws SecurityException 

Source Link

Document

Add a log Handler to receive logging messages.

Usage

From source file:uk.org.lidalia.sysoutslf4j.integration.TestSysOutOverSlf4J.java

@Test
public void juliConsoleAppenderStillLogsToConsole() throws Exception {
    OutputStream newSysErr = setUpMockSystemOutput(SystemOutput.ERR);
    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();

    java.util.logging.Logger log = java.util.logging.Logger.getLogger("");
    for (Handler handler : log.getHandlers()) {
        log.removeHandler(handler);//from  w w w .j a v a 2  s  .c  o m
    }
    log.addHandler(new ConsoleHandler());
    log.info("Should reach the old syserr");

    assertThat(newSysErr.toString(), containsString("INFO: Should reach the old syserr"));
}

From source file:bookkeepr.BookKeepr.java

/**
 * This loads the configuration file and sets the intial settings. 
 *//* w w  w. j a  va2  s . co m*/
public BookKeepr(File configFile) {

    try {
        this.configFile = configFile;
        if (!configFile.exists()) {
            config = new BookkeeprConfig();
            config.setOriginId(0);
            saveConfig();
        }
        config = (BookkeeprConfig) XMLReader.read(new FileInputStream(configFile));
        if (config.getOriginId() < 0 || config.getOriginId() > 255) {
            config.setOriginId(0);

        }
        if (config.getOriginId() == 0) {
            Logger.getLogger(BookKeepr.class.getName()).log(Level.INFO,
                    "Client mode active, creation or modification disabled");
        }

        statusMon = new BookKeeprStatusMonitor();
        Logger logger = Logger.getLogger("bookkeepr");
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        logger.addHandler(statusMon);
    } catch (SAXException ex) {
        Logger.getLogger(BookKeepr.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(BookKeepr.class.getName()).log(Level.SEVERE, null, ex);
    }
    for (int i = 0; i < 20; i++) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpClientParams.setRedirecting(httpclient.getParams(), false);
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
        if (config.getProxyUrl() != null) {
            final HttpHost proxy = new HttpHost(config.getProxyUrl(), config.getProxyPort(), "http");
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        httpClients.add(httpclient);
    }

}

From source file:org.mp4parser.tools.Main.java

public Logger setupLogger() {
    Logger logger = Logger.getLogger("tools");
    InputStream stream;/*  ww  w .  ja v  a 2  s  . co  m*/
    if (verbose) {
        stream = Main.class.getResourceAsStream("/log-verbose.properties");
    } else {
        stream = Main.class.getResourceAsStream("/log.properties");
    }
    try {
        LogManager.getLogManager().readConfiguration(stream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    logger.setLevel(Level.FINE);
    logger.addHandler(new java.util.logging.ConsoleHandler());
    logger.setUseParentHandlers(false);

    return logger;
}

From source file:util.Log.java

/**
 * Gera um arquivo log dentro da Pasta Logger que fica na Pasta principal do
 * Usuario.//from   w  w w .  j a v  a  2  s  .  c om
 *
 * @param className
 * @param ex
 */
public static void relatarExcecao(String className, Exception ex) {
    try {
        /*
         * Informamos qual o nome do Logger, que no caso vai ser o nome da
         * Classe que acontecer a exceo
         */
        Logger log = Logger.getLogger(className);
        /*
         * Variavel que vai conter qual a pasta do sistema que liga ao
         * usuario, por padro ser do sistema operacional Windows
         */
        String systemPath = "/Users/";
        /* Se for outro sistema operacional */
        if (System.getProperty("os.name").startsWith("Linux")) {
            systemPath = "/home/";
        }
        /* Pasta onde vamos colocar os Logs */
        File pastaLog = new File(systemPath + System.getProperty("user.name") + "/Logger");
        if (!pastaLog.exists()) {
            pastaLog.mkdir();
        }
        String arquivoDir = pastaLog.getAbsolutePath() + "/LOG_"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM_HH-mm-ss")) + ".log";
        /* Classe responsavel por escrever o arquivo */
        FileHandler escrever = new FileHandler(arquivoDir, true);
        /*
         * Precisamos informar como ser escrito(formato) as excees, Vamos
         * Utilizar uma Classe j pronta para isso a Classe SimpleFormatter
         */
        escrever.setFormatter(new SimpleFormatter());
        /*
         * Adicionamos ao nosso log a Classe que vai escrever a exceo que
         * for gerada
         */
        log.addHandler(escrever);

        /*
         * Geramos o Log, passamos que ser de Nivel Severe(Alto), e
         * passamos a exceo para ele
         */
        log.log(Level.SEVERE, null, ex);

        /* Finalizamos a escrita */
        escrever.flush();
        escrever.close();
        /*Envia por email a exceo*/
        Log.relatarExceptionEmail(className, ex.getMessage(), arquivoDir);

    } catch (IOException | SecurityException e) {
        Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, e);
    }
}

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);
                }/*from  w  w  w.j  ava  2  s .  com*/

            }
        }
    });

    return bean;
}

From source file:com.google.zxing.web.DecodeServlet.java

@Override
public void init(ServletConfig servletConfig) throws ServletException {
    Logger logger = Logger.getLogger("com.google.zxing");
    ServletContext context = servletConfig.getServletContext();
    logger.addHandler(new ServletContextLogHandler(context));
    File repository = (File) context.getAttribute("javax.servlet.context.tempdir");
    FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context);
    diskFileItemFactory = new DiskFileItemFactory(1 << 16, repository);
    diskFileItemFactory.setFileCleaningTracker(fileCleaningTracker);

    URL blockURL = context.getClassLoader().getResource("/private/uri-block-substrings.txt");
    if (blockURL == null) {
        blockedURLSubstrings = Collections.emptyList();
    } else {/*from  www .  ja  v a2  s.co  m*/
        try {
            blockedURLSubstrings = Resources.readLines(blockURL, StandardCharsets.UTF_8);
        } catch (IOException ioe) {
            throw new ServletException(ioe);
        }
        log.info("Blocking URIs containing: " + blockedURLSubstrings);
    }
}

From source file:de.ailis.jasdoc.Main.java

/**
 * Initializes logging./*from  w  w  w. j  a  v  a 2  s  .  c o m*/
 */
private void initLogging() {
    final Logger logger = Logger.getLogger("de.ailis.jasdoc");
    logger.setUseParentHandlers(false);
    final Handler handler = new LogHandler();
    handler.setFilter(null);
    handler.setFormatter(new LogFormatter(this.debug));
    if (this.debug)
        handler.setLevel(Level.ALL);
    else if (this.quiet)
        handler.setLevel(Level.WARNING);
    else
        handler.setLevel(Level.INFO);
    logger.setFilter(null);
    logger.addHandler(handler);
    Logger.getLogger("").setLevel(handler.getLevel());
}

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   ww  w.j  a  va 2 s .  c om
        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:brut.apktool.Main.java

private static void setupLogging(Verbosity verbosity) {
    Logger logger = Logger.getLogger("");
    for (Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);// w ww  .ja va2 s  .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");
            }
        });
    }
}

From source file:org.springframework.shell.core.JLineShell.java

public void run() {
    reader = createConsoleReader();//from w w w.j  a  va  2s .c om

    setPromptPath(null);

    JLineLogHandler handler = new JLineLogHandler(reader, this);
    JLineLogHandler.prohibitRedraw(); // Affects this thread only
    Logger mainLogger = Logger.getLogger("");
    removeHandlers(mainLogger);
    mainLogger.addHandler(handler);

    reader.addCompletor(new JLineCompletorAdapter(getParser()));

    reader.setBellEnabled(true);
    if (Boolean.getBoolean("jline.nobell")) {
        reader.setBellEnabled(false);
    }

    // reader.setDebug(new PrintWriter(new FileWriter("writer.debug", true)));

    openFileLogIfPossible();
    this.reader.getHistory().setMaxSize(getHistorySize());
    // Try to build previous command history from the project's log
    String[] filteredLogEntries = filterLogEntry();
    for (String logEntry : filteredLogEntries) {
        reader.getHistory().addToHistory(logEntry);
    }

    flashMessageRenderer();
    flash(Level.FINE, this.getProductName() + " " + this.getVersion(), Shell.WINDOW_TITLE_SLOT);
    printBannerAndWelcome();

    String startupNotifications = getStartupNotifications();
    if (StringUtils.hasText(startupNotifications)) {
        logger.info(startupNotifications);
    }

    setShellStatus(Status.STARTED);

    try {
        // Monitor CTRL+C initiated shutdowns (ROO-1599)
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            public void run() {
                shutdownHookFired = true;
            }
        }, getProductName() + " JLine Shutdown Hook"));
    } catch (Throwable t) {
    }

    // Handle any "execute-then-quit" operation

    String rooArgs = System.getProperty("roo.args");
    if (rooArgs != null && !"".equals(rooArgs)) {
        setShellStatus(Status.USER_INPUT);
        boolean success = executeCommand(rooArgs);
        if (exitShellRequest == null) {
            // The command itself did not specify an exit shell code, so we'll fall back to something sensible here
            executeCommand("quit"); // ROO-839
            exitShellRequest = success ? ExitShellRequest.NORMAL_EXIT : ExitShellRequest.FATAL_EXIT;
        }
        setShellStatus(Status.SHUTTING_DOWN);
    } else {
        // Normal RPEL processing
        promptLoop();
    }

}