Java: Stream Handler for Logger








        Logger logger = Logger.getLogger("daris-download");
        logger.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        /*
         * file handler
         */
        FileHandler fileHandler = new FileHandler(
                "%h/.daris/daris-download.%g.log", 5000000, 2);
        fileHandler.setLevel(Level.ALL);
        fileHandler.setFormatter(new Formatter() {

            @Override
            public String format(LogRecord record) {
                StringBuilder sb = new StringBuilder();
                sb.append(new Date(record.getMillis())).append(" ");
                sb.append("[thread: ").append(record.getThreadID())
                        .append("] ");
                sb.append(record.getLevel().getName()).append(" ");
                sb.append(record.getMessage());
                sb.append("\n");
                return sb.toString();
            }
        });
        logger.addHandler(fileHandler);
        /*
         * console handler
         */
        StreamHandler consoleHandler = new StreamHandler(System.out,
                new Formatter() {
                    @Override
                    public String format(LogRecord record) {
                        return record.getMessage() + "\n";
                    }
                }) {
            @Override
            public synchronized void publish(LogRecord record) {
                super.publish(record);
                super.flush();
            }
        };
        consoleHandler.setLevel(Level.INFO);
        logger.addHandler(consoleHandler);



No comments:

Post a Comment