List of usage examples for java.util.logging LogRecord getMillis
public long getMillis()
From source file:MyHtmlFormatter.java
public String format(LogRecord rec) { StringBuffer buf = new StringBuffer(1000); if (rec.getLevel().intValue() >= Level.WARNING.intValue()) { buf.append("<b>"); buf.append(rec.getLevel());/*w w w .j a va2 s. c o m*/ buf.append("</b>"); } else { buf.append(rec.getLevel()); } buf.append(' '); buf.append(rec.getMillis()); buf.append(' '); buf.append(formatMessage(rec)); buf.append('\n'); return buf.toString(); }
From source file:NemaLogFormatter.java
/** Formats the record. * // w ww . j ava2 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.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 ww . j a va 2 s.c om }; 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:majordodo.task.BrokerTestUtils.java
@Before public void brokerTestUtilsBefore() throws Exception { // Setup exception handler Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override//from www . j ava 2 s . c o m public void uncaughtException(Thread t, Throwable e) { System.err.println("uncaughtException from thread " + t.getName() + ": " + e); e.printStackTrace(); unhandledExceptions.add(e); } }); // Setup Logger System.out.println("Setup logger to level " + logLevel.getName()); java.util.logging.LogManager.getLogManager().reset(); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(logLevel); ch.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " [" + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] " + record.getLoggerName() + ": " + formatMessage(record) + "\n"; } }); java.util.logging.Logger.getLogger("").setLevel(logLevel); java.util.logging.Logger.getLogger("").addHandler(ch); // Initialize groupsMap groupsMap.clear(); groupsMap.put(userId, group); // Setup workdir Path mavenTargetDir = Paths.get("target").toAbsolutePath(); workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime()); if (startBroker) { broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker.startAsWritable(); server = new NettyChannelAcceptor(broker.getAcceptor()); server.start(); } if (startReplicatedBrokers) { zkServer = new ZKTestEnv(folderZk.getRoot().toPath()); zkServer.startBookie(); // Broker 1 broker1 = new Broker(broker1Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker1Host, broker1Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker1.startAsWritable(); server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port); server1.start(); // Broker 2 broker2 = new Broker(broker2Config, new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(), folderSnapshots.newFolder().toPath(), BrokerHostData.formatHostdata( new BrokerHostData(broker2Host, broker2Port, "", false, null)), false), new TasksHeap(1000, createTaskPropertiesMapperFunction())); broker2.start(); server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port); server2.start(); // Broker locator brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath()); } }
From source file:org.fornax.cartridges.sculptor.smartclient.server.util.UnifiedFormatter.java
@Override public String format(LogRecord record) { String username = "ANONYMOUS"; if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof User) { username = ((User) principal).getUsername(); } else {//from w ww .ja va 2s . c om username = principal.toString(); } } int dotIndex = record.getSourceClassName().lastIndexOf("."); String className = record.getSourceClassName().substring(dotIndex != -1 ? dotIndex + 1 : 0); String msg = record.getMessage(); if (record.getParameters() != null && record.getParameters().length > 0) { msg = MessageFormat.format(record.getMessage(), record.getParameters()); } if (record.getThrown() != null) { Throwable thrown = record.getThrown(); StringWriter result = new StringWriter(); thrown.printStackTrace(new PrintWriter(result)); result.flush(); msg += "\n" + result.getBuffer(); } return FST + dateFormat.format(record.getMillis()) + FET + FSEP + RST + FST + record.getLevel() + FET + FSEP + FST + className + "." + record.getSourceMethodName() + FET + FSEP + FST + username + FET + FSEP + FST + record.getThreadID() + FET + FSEP + FST + msg + FET + RET; }
From source file:alma.acs.logging.adapters.JacORBFilter.java
/** * Discards less useful or misleading Jacorb logs based on the message. * <p>//ww w . j av a2s . co m * TODO-: to improve performance, we could instead match file and line, but then would have to update * that information with the next jacorb code change. * The implementation already minimizes string comparison by checking only those messages that can occur at the given log level. * <p> * TODO: Add repeat guard based on the message, e.g. using MultipleRepeatGuard from jacsutil. */ public boolean isLoggable(LogRecord record) { String message = record.getMessage(); boolean isLoggable = true; if (record.getLevel().intValue() == Level.FINE.intValue()) { // map from FINE to FINEST if (message.startsWith("POA ") && (message.endsWith("shutdown is in progress") || message.endsWith("destruction is apparent") || message.endsWith("clear up the queue...") || message.endsWith("... done") || message.endsWith("stop the request controller") || message.endsWith("etherialize all servants ..."))) { record.setLevel(Level.FINEST); } else if (message.startsWith("get_policy_overrides returns") || message.startsWith("read GIOP message of size") || message.startsWith("wrote GIOP message of size")) { // From ACS unit tests it seems that this message is totally harmless, // caused by a Corba stub calling org.jacorb.orb.Delegate#getRelativeRoundtripTimeout() // and asking for the RELATIVE_RT_TIMEOUT_POLICY_TYPE policy. // We do not fully discard the log though because it may have other causes at the AOS. record.setLevel(Level.FINEST); // // Enable the following 2 lines to investigate for http://jira.alma.cl/browse/COMP-8302, to see where all these logs come from // String stackTrace = org.apache.commons.lang.exception.ExceptionUtils.getStackTrace(new Throwable()); // System.out.println("Hack for COMP-8302 debugging: 'get_policy_overrides returns' message logged with trace " + stackTrace); } // from FINE to discard else isLoggable = !(message.endsWith("_invoke: queuing request") || message.indexOf("is queued (queue size:") > 0 || message.endsWith("trying to get a RequestProcessor") || message.endsWith("waiting for queue") || message.endsWith("with request processing") || // for "starts...", "ends..." message.endsWith("invokeOperation on servant (stream based)") || message.endsWith("reset a previous completion call") || message.startsWith("Delegate.getReference") || message.startsWith("Received CodeSetContext. Using") || message.startsWith("ClientConnectionManager: releasing ClientGIOPConnection") || message.startsWith("Delegate released!") || message.endsWith(": streamClosed()") // findPOA: impl_name mismatch ); } else if (record.getLevel().intValue() == Level.INFO.intValue()) { // from INFO to CONFIG if (message.indexOf("(C) The JacORB project") > 0 || message.startsWith("Received CloseConnection on ClientGIOPConnection") || message.startsWith("prepare ORB for shutdown") || message.startsWith("Client-side TCP transport to") || message.startsWith("ORB going down...") || message.startsWith("ORB run") || // also "ORB run, exit" message.equals("ORB shutdown complete") || (message.startsWith("POA ") && (message.endsWith("destroyed"))) || message.startsWith("Opened new server-side TCP/IP")) { record.setLevel(Level.CONFIG); } // from INFO to FINEST else if (message.startsWith("Connected to ") || message.startsWith("Closed server-side transport to") || (message.startsWith("POA ") && (message.endsWith("up the queue ...") || message.endsWith("... done"))) || message.startsWith("Retrying to connect to") || message.startsWith("ClientConnectionManager: created new ClientGIOPConnection") || message.startsWith("ClientConnectionManager: found ClientGIOPConnection") || message.startsWith("Initialising ORB with ID") || message.startsWith("Set default native char codeset to") || message.startsWith("Set default native wchar codeset to") || message.equals("Listener exiting") || message.equals("ConsumerTie exited")) { record.setLevel(Level.FINEST); } // from INFO to stdout shortcut else if ((message.startsWith("ClientGIOPConnection to ") || message.startsWith("ServerGIOPConnection to ")) && message.contains(" BufferDump:\n") || message.startsWith("sendMessages(): ")) { // The jacorb dumps from org.jacorb.orb.etf.StreamConnectionBase.flush() // and org.jacorb.orb.giop.GIOPConnection.getMessage() are very special. // They get enabled via properties 'jacorb.debug.dump_outgoing_messages' // and 'jacorb.debug.dump_incoming_messages' and logged as INFO. // If they are enabled, we still want to see them only in the local logs // (otherwise there may be even "positive feedback" leading to log explosion). // A cleaner concept would be to only flag this LogRecord as "log only locally", // return "isLoggable = true" and leave the rest to the local and remote log handlers. // The fact that we are dealing with a generic LogRecord (not AcsLogRecord) makes this // option also ugly though (LogParameterUtil tricks), and thus we just print and drop // the log right away here. String timeStamp = IsoDateFormat.formatDate(new Date(record.getMillis())); System.out.println(timeStamp + " " + message); isLoggable = false; } // from INFO to discard else isLoggable = !(message.startsWith("oid: ") || message.startsWith("InterceptorManager started with") || message.startsWith("Using server ID (")); } else if (record.getLevel().intValue() == Level.WARNING.intValue()) { // from WARNING to CONFIG // if (message.indexOf("") > 0) { // record.setLevel(Level.CONFIG); // } // // from WARNING to FINEST // else if (message.startsWith("")) { // record.setLevel(Level.FINEST); // } // from WARNING to discard // else isLoggable = !(message.startsWith("no adapter activator exists for") // client tries to find remote poa locally and then complains if not there... ); } else if (record.getLevel().intValue() == Level.SEVERE.intValue()) { // HSO 07-02-19: thought this adapter activator crap was logged as warning, but now it showed up in jcont test as ACS-level "Emergency", which is JDK-SEVERE isLoggable = !(message.startsWith("no adapter activator exists for") // client tries to find remote poa locally and then complains if not there... ); } // filter by possibly modified log level if (isLoggable && record.getLevel().intValue() < this.logLevel) { isLoggable = false; } // if (!isLoggable) { // System.out.println("dropping JacORB message " + message + " with Level " + record.getLevel().getName()); // } // Remove non-ascii chars from the log message, which seems to occur only in logs coming from jacorb, // see http://jira.alma.cl/browse/COMP-3243 // For simplicity we blank all non-ascii-7-printable chars except newline and tab, // at the low risk of erroneously blanking more sophisticated (Umlaut etc) chars that jacorb may send us. // If that turns out to be the case, and the encoding turns out as unicode, then see http://en.wikipedia.org/wiki/C0_and_C1_control_codes if (isLoggable && message != null) { String message2 = null; int mlen = message.length(); for (int i = 0; i < mlen; i++) { char ch = message.charAt(i); if ((ch < 32 || ch >= 127) && ch != '\n' && ch != '\t') { // got a bad char if (message2 == null) { // copy the leading good chars only if needed, to improve performance message2 = message.substring(0, i); } // blank the bad char message2 += '#'; } else if (message2 != null) { message2 += ch; } } if (message2 != null) { record.setMessage(message2); } } return isLoggable; }
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(//from www .jav a 2 s . c om 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(); }
From source file:org.dstadler.commons.logging.jdk.PatternFormatter.java
@Override public String format(LogRecord record) { Date time = new Date(record.getMillis()); String formattedTime = dateFormat.format(time); final String logMessage; if (record.getThrown() == null) { Object[] log = { record.getLoggerName(), record.getLevel(), formattedTime, record.getMessage(), record.getSourceClassName(), record.getSourceMethodName() }; logMessage = logMessageFormat.format(log); } else {//from w w w.j ava2 s . c o m String stack = getStackLayout(record.getThrown(), ""); Object[] log = { record.getLoggerName(), record.getLevel(), formattedTime, record.getMessage(), record.getSourceClassName(), record.getSourceMethodName(), record.getThrown().getMessage(), stack }; logMessage = exceptionMessageFormat.format(log); } return logMessage; }
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/*from w w w. j ava 2 s . com*/ 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.hillview.utils.HillviewLogger.java
/** * Create a Hillview logger./* w w w . j a v a2s . c o 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); }