Example usage for java.util.logging LogRecord getMessage

List of usage examples for java.util.logging LogRecord getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Get the "raw" log message, before localization or formatting.

Usage

From source file:NemaLogFormatter.java

/** Formats the record.
 * /*from ww w.  j  a v a2 s.  co m*/
 * @param record The log record to format
 * @return The formated record
 */
@Override
public String format(LogRecord record) {
    String className = record.getSourceClassName();

    String threadName = Thread.currentThread().getName();
    if (threadName != null && threadName.length() > MAX_THREAD_NAME_LENGTH) {
        threadName = threadName.substring(threadName.length() - MAX_THREAD_NAME_LENGTH);
    }

    String sTimeStamp = FORMATER.format(new Date(record.getMillis()));

    return sTimeStamp + "::" + record.getLevel() + ":  " + record.getMessage() + "  "
            + ((bClass) ? " [" + className + "." + record.getSourceMethodName() + "]" : "")
            + ((bClass) ? " <" + threadName + ":" + record.getThreadID() + ">" : "") + NEW_LINE;
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * Inits the search logger.//  ww w .  j a va2 s  .  c om
 */
private void initSearchLogger(Connection connection) {
    Logger logger = Logger.getAnonymousLogger();
    loggers.put(connection.getId(), logger);
    logger.setLevel(Level.ALL);

    String logfileName = ConnectionManager.getSearchLogFileName(connection);
    try {
        FileHandler fileHandler = new FileHandler(logfileName, getFileSizeInKb() * 1000, getFileCount(), true);
        fileHandlers.put(connection.getId(), fileHandler);
        fileHandler.setFormatter(new Formatter() {
            public String format(LogRecord record) {
                return record.getMessage();
            }
        });
        logger.addHandler(fileHandler);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.archive.crawler.reporting.CrawlerLoggerModule.java

public Logger setupSimpleLog(String logName) {
    Logger logger = Logger.getLogger(logName + ".log");

    Formatter f = new Formatter() {
        public String format(java.util.logging.LogRecord record) {
            return ArchiveUtils.getLog17Date(record.getMillis()) + " " + record.getMessage() + '\n';
        }/*  w w  w .  ja v a2  s . c o m*/
    };

    ConfigPath logPath = new ConfigPath(logName + ".log", logName + ".log");
    logPath.setBase(getPath());
    try {
        setupLogFile(logger, logPath.getFile().getAbsolutePath(), f, true);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    return logger;
}

From source file:com.valygard.aohruthless.Joystick.java

/**
 * Not satisfied with global logging, which can become cluttered and messy
 * with many plugins or players using commands, etc, the Bukkit logger will
 * log all relevant information to a log file. This log file can be found in
 * the plugin data folder, in the subdirectory <i>logs</i>.
 * <p>// w  ww  .  jav  a  2 s  . co m
 * The log file, <i>joystick.log</i>, will not be overriden. The logger will
 * simply append new information if the file already exists. All messages
 * will be logged in the format:<br>
 * [month-day-year hr-min-sec] (level): (message), where level is the
 * {@link LogRecord#getLevel()} and the message is the
 * {@link LogRecord#getMessage()}.
 * </p>
 * 
 * @return the created FileHandler, null if a SecurityException or
 *         IOException were thrown and handled.
 */
private FileHandler setupLogger() {
    File dir = new File(getDataFolder() + File.separator + "logs");
    dir.mkdirs();
    try {
        FileHandler handler = new FileHandler(dir + File.separator + "joystick.log", true);
        getLogger().addHandler(handler);
        handler.setFormatter(new SimpleFormatter() {

            @Override
            public String format(LogRecord record) {
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("[MM-dd-yyyy HH:mm:ss]");
                return df.format(date) + " " + record.getLevel() + ":"
                // org.apache.commons.lang
                        + StringUtils.replace(record.getMessage(), "[Joystick]", "")
                        + System.getProperty("line.separator");
            }
        });
        return handler;
    } catch (SecurityException | IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.hillview.utils.HillviewLogger.java

/**
 * Create a Hillview logger./* ww  w .  ja v a2  s. co m*/
 * @param role      Who is doing the logging: web server, worker, test, etc.
 * @param filename  File where logs are to be written.  If null logs will be written to the
 *                  console.
 */
private HillviewLogger(String role, @Nullable String filename) {
    // Disable all default logging
    LogManager.getLogManager().reset();
    this.logger = Logger.getLogger("Hillview");
    this.machine = this.checkCommas(Utilities.getHostName());
    this.role = this.checkCommas(role);
    this.logger.setLevel(Level.INFO);

    Formatter form = new SimpleFormatter() {
        final String[] components = new String[5];
        final String newline = System.lineSeparator();
        private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        @Override
        public synchronized String format(LogRecord record) {
            this.components[0] = HillviewLogger.this.checkCommas(df.format(new Date(record.getMillis())));
            this.components[1] = HillviewLogger.this.role;
            this.components[2] = HillviewLogger.this.checkCommas(record.getLevel().toString());
            this.components[3] = HillviewLogger.this.machine;
            this.components[4] = record.getMessage();
            String result = String.join(",", components);
            return result + this.newline;
        }
    };

    Handler handler;
    if (filename != null) {
        try {
            handler = new FileHandler(filename);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        handler = new ConsoleHandler();
    }
    handler.setFormatter(form);
    logger.addHandler(handler);
    File currentDirectory = new File(new File(".").getAbsolutePath());
    this.info("Starting logger", "Working directory: {0}", currentDirectory);
}

From source file:ch.jamiete.hilda.music.MusicLogFormat.java

@Override
public final String format(final LogRecord record) {
    String log = "";

    log += this.sdf.format(new Date(record.getMillis()));
    log += " [" + record.getLevel().getLocalizedName().toUpperCase() + ']';

    if (record.getSourceClassName() != null) {
        final String[] split = record.getSourceClassName().split("\\.");
        log += " [" + split[(split.length == 1) ? 0 : (split.length - 1)] + ']';
    }//from w  w w .j av  a2s . c  om

    if (record.getSourceMethodName() != null) {
        log += " (" + record.getSourceMethodName() + ')';
    }

    log += ' ' + record.getMessage();

    if (record.getThrown() != null) {
        /*log += "\n" + record.getThrown().getMessage();
                
        for (StackTraceElement element : record.getThrown().getStackTrace()) {
        log += "\n" + element.toString();
        }*/
        log += '\n' + ExceptionUtils.getStackTrace(record.getThrown());
    }

    log += System.getProperty("line.separator");

    return log;
}

From source file:com.liferay.httpservice.internal.servlet.BundleServletContextTest.java

@Test
public void testGetFilterChain() throws Exception {
    mockBundleWiring();//from ww  w  .j  av a  2s.c  o m

    List<LogRecord> logRecords = JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(),
            Level.INFO);

    String cssFilterName = "CSS Filter";

    registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

    String jsFilterName = "JS Filter";

    registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

    FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js");

    Assert.assertNotNull(filterChain);

    filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

    Assert.assertEquals(1, logRecords.size());

    LogRecord logRecord = logRecords.get(0);

    Assert.assertEquals(jsFilterName, logRecord.getMessage());

    verifyBundleWiring();
}

From source file:com.liferay.portal.http.service.internal.servlet.BundleServletContextTest.java

@Test
public void testGetFilterChain() throws Exception {
    mockBundleWiring();/*from  w  w w  .  ja  va 2 s. c o  m*/

    List<LogRecord> logFilterRecords = JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(),
            Level.INFO);

    String cssFilterName = "CSS Filter";

    registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

    String jsFilterName = "JS Filter";

    registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

    registerServlet("Sample Servlet", "/");

    FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js", DispatcherType.REQUEST);

    Assert.assertNotNull(filterChain);

    filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

    Assert.assertEquals(1, logFilterRecords.size());

    LogRecord logRecord = logFilterRecords.get(0);

    Assert.assertEquals(jsFilterName, logRecord.getMessage());

    verifyBundleWiring();
}

From source file:org.ensembl.healthcheck.StandaloneTestRunner.java

public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger(StandaloneTestRunner.class.getCanonicalName());
        ConsoleHandler localConsoleHandler = new ConsoleHandler();
        localConsoleHandler.setFormatter(new Formatter() {
            DateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

            @Override//  w ww . j a va2s .  c om
            public String format(LogRecord record) {
                return String.format("%s %s %s : %s%n", format.format(new Date(record.getMillis())),
                        record.getSourceClassName(), record.getLevel().toString(), record.getMessage());
            }
        });
        if (options.isVerbose()) {
            localConsoleHandler.setLevel(Level.ALL);
            logger.setLevel(Level.ALL);
        } else {
            localConsoleHandler.setLevel(Level.INFO);
            logger.setLevel(Level.INFO);
        }
        logger.setUseParentHandlers(false);
        logger.addHandler(localConsoleHandler);
    }
    return logger;
}

From source file:org.apache.qpid.amqp_1_0.client.Util.java

protected Util(String[] args) {
    CommandLineParser cmdLineParse = new PosixParser();

    Options options = new Options();
    options.addOption("h", "help", false, "show this help message and exit");
    options.addOption(OptionBuilder.withLongOpt("host").withDescription("host to connect to (default 0.0.0.0)")
            .hasArg(true).withArgName("HOST").create('H'));
    options.addOption(/* w  w  w .jav  a2 s .c  o m*/
            OptionBuilder.withLongOpt("username").withDescription("username to use for authentication")
                    .hasArg(true).withArgName("USERNAME").create('u'));
    options.addOption(
            OptionBuilder.withLongOpt("password").withDescription("password to use for authentication")
                    .hasArg(true).withArgName("PASSWORD").create('w'));
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("port to connect to (default 5672)")
            .hasArg(true).withArgName("PORT").create('p'));
    options.addOption(OptionBuilder.withLongOpt("frame-size").withDescription("specify the maximum frame size")
            .hasArg(true).withArgName("FRAME_SIZE").create('f'));
    options.addOption(OptionBuilder.withLongOpt("container-name").withDescription("Container name").hasArg(true)
            .withArgName("CONTAINER_NAME").create('C'));

    options.addOption(OptionBuilder.withLongOpt("ssl").withDescription("Use SSL").create('S'));

    options.addOption(
            OptionBuilder.withLongOpt("remote-hostname").withDescription("hostname to supply in the open frame")
                    .hasArg(true).withArgName("HOST").create('O'));

    if (hasBlockOption())
        options.addOption(
                OptionBuilder.withLongOpt("block").withDescription("block until messages arrive").create('b'));

    if (hasCountOption())
        options.addOption(
                OptionBuilder.withLongOpt("count").withDescription("number of messages to send (default 1)")
                        .hasArg(true).withArgName("COUNT").create('c'));
    if (hasModeOption())
        options.addOption(OptionBuilder.withLongOpt("acknowledge-mode")
                .withDescription("acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once")
                .hasArg(true).withArgName("MODE").create('k'));

    if (hasSubjectOption())
        options.addOption(OptionBuilder.withLongOpt("subject").withDescription("subject message property")
                .hasArg(true).withArgName("SUBJECT").create('s'));

    if (hasSingleLinkPerConnectionMode())
        options.addOption(OptionBuilder.withLongOpt("single-link-per-connection")
                .withDescription("acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once")
                .hasArg(false).create('Z'));

    if (hasFilterOption())
        options.addOption(OptionBuilder.withLongOpt("filter")
                .withDescription("filter, e.g. exact-subject=hello; matching-subject=%.a.#").hasArg(true)
                .withArgName("<TYPE>=<VALUE>").create('F'));

    if (hasTxnOption()) {
        options.addOption("x", "txn", false, "use transactions");
        options.addOption(
                OptionBuilder.withLongOpt("batch-size").withDescription("transaction batch size (default: 1)")
                        .hasArg(true).withArgName("BATCH-SIZE").create('B'));
        options.addOption(OptionBuilder.withLongOpt("rollback-ratio")
                .withDescription("rollback ratio - must be between 0 and 1 (default: 0)").hasArg(true)
                .withArgName("RATIO").create('R'));
    }

    if (hasLinkDurableOption()) {
        options.addOption("d", "durable-link", false, "use a durable link");
    }

    if (hasStdInOption())
        options.addOption("i", "stdin", false, "read messages from stdin (one message per line)");

    options.addOption(
            OptionBuilder.withLongOpt("trace").withDescription("trace logging specified categories: RAW, FRM")
                    .hasArg(true).withArgName("TRACE").create('t'));
    if (hasSizeOption())
        options.addOption(
                OptionBuilder.withLongOpt("message-size").withDescription("size to pad outgoing messages to")
                        .hasArg(true).withArgName("SIZE").create('z'));

    if (hasResponseQueueOption())
        options.addOption(
                OptionBuilder.withLongOpt("response-queue").withDescription("response queue to reply to")
                        .hasArg(true).withArgName("RESPONSE_QUEUE").create('r'));

    if (hasLinkNameOption()) {
        options.addOption(OptionBuilder.withLongOpt("link").withDescription("link name").hasArg(true)
                .withArgName("LINK").create('l'));
    }

    if (hasWindowSizeOption()) {
        options.addOption(OptionBuilder.withLongOpt("window-size").withDescription("credit window size")
                .hasArg(true).withArgName("WINDOW-SIZE").create('W'));
    }

    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParse.parse(options, args);

    } catch (ParseException e) {
        printUsage(options);
        System.exit(-1);
    }

    if (cmdLine.hasOption('h') || cmdLine.getArgList().isEmpty()) {
        printUsage(options);
        System.exit(0);
    }
    _host = cmdLine.getOptionValue('H', "0.0.0.0");
    _remoteHost = cmdLine.getOptionValue('O', null);
    String portStr = cmdLine.getOptionValue('p', "5672");
    String countStr = cmdLine.getOptionValue('c', "1");

    _useSSL = cmdLine.hasOption('S');

    if (hasWindowSizeOption()) {
        String windowSizeStr = cmdLine.getOptionValue('W', "100");
        _windowSize = Integer.parseInt(windowSizeStr);
    }

    if (hasSubjectOption()) {
        _subject = cmdLine.getOptionValue('s');
    }

    if (cmdLine.hasOption('u')) {
        _username = cmdLine.getOptionValue('u');
    }

    if (cmdLine.hasOption('w')) {
        _password = cmdLine.getOptionValue('w');
    }

    if (cmdLine.hasOption('F')) {
        _filter = cmdLine.getOptionValue('F');
    }

    _port = Integer.parseInt(portStr);

    _containerName = cmdLine.getOptionValue('C');

    if (hasBlockOption())
        _block = cmdLine.hasOption('b');

    if (hasLinkNameOption())
        _linkName = cmdLine.getOptionValue('l');

    if (hasLinkDurableOption())
        _durableLink = cmdLine.hasOption('d');

    if (hasCountOption())
        _count = Integer.parseInt(countStr);

    if (hasStdInOption())
        _useStdIn = cmdLine.hasOption('i');

    if (hasSingleLinkPerConnectionMode())
        _useMultipleConnections = cmdLine.hasOption('Z');

    if (hasTxnOption()) {
        _useTran = cmdLine.hasOption('x');
        _batchSize = Integer.parseInt(cmdLine.getOptionValue('B', "1"));
        _rollbackRatio = Double.parseDouble(cmdLine.getOptionValue('R', "0"));
    }

    if (hasModeOption()) {
        _mode = AcknowledgeMode.ALO;

        if (cmdLine.hasOption('k')) {
            _mode = AcknowledgeMode.valueOf(cmdLine.getOptionValue('k'));
        }
    }

    if (hasResponseQueueOption()) {
        _responseQueue = cmdLine.getOptionValue('r');
    }

    _frameSize = Integer.parseInt(cmdLine.getOptionValue('f', "65536"));

    if (hasSizeOption()) {
        _messageSize = Integer.parseInt(cmdLine.getOptionValue('z', "-1"));
    }

    String categoriesList = cmdLine.getOptionValue('t');
    String[] categories = categoriesList == null ? new String[0] : categoriesList.split("[, ]");
    for (String cat : categories) {
        if (cat.equalsIgnoreCase("FRM")) {
            FRAME_LOGGER.setLevel(Level.FINE);
            Formatter formatter = new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    return "[" + record.getMillis() + " FRM]\t" + record.getMessage() + "\n";
                }
            };
            for (Handler handler : FRAME_LOGGER.getHandlers()) {
                FRAME_LOGGER.removeHandler(handler);
            }
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.FINE);
            handler.setFormatter(formatter);
            FRAME_LOGGER.addHandler(handler);
        } else if (cat.equalsIgnoreCase("RAW")) {
            RAW_LOGGER.setLevel(Level.FINE);
            Formatter formatter = new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    return "[" + record.getMillis() + " RAW]\t" + record.getMessage() + "\n";
                }
            };
            for (Handler handler : RAW_LOGGER.getHandlers()) {
                RAW_LOGGER.removeHandler(handler);
            }
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.FINE);
            handler.setFormatter(formatter);
            RAW_LOGGER.addHandler(handler);
        }
    }

    _args = cmdLine.getArgs();

}