Java Code Examples for java.util.logging.Logger#log()

The following examples show how to use java.util.logging.Logger#log() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OsgiLogHandlerTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void requireThatLogRecordsArePublishedToLogService() {
    MyLogService logService = new MyLogService();
    Logger log = newLogger(logService);

    log.log(Level.INFO, "foo");
    assertEquals(OsgiLogHandler.toServiceLevel(Level.INFO), logService.lastLevel);
    assertEquals("foo", logService.lastMessage);
    assertNull(logService.lastThrowable);

    Throwable t = new Throwable();
    log.log(Level.SEVERE, "bar", t);
    assertEquals(OsgiLogHandler.toServiceLevel(Level.SEVERE), logService.lastLevel);
    assertEquals("bar", logService.lastMessage);
    assertEquals(t, logService.lastThrowable);
}
 
Example 2
Source File: WatchdogThread.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
private static void dumpThread(ThreadInfo thread, Logger log) {
    log.log(Level.SEVERE, "------------------------------");
    //
    log.log(Level.SEVERE, "Current Thread: " + thread.getThreadName());
    log.log(Level.SEVERE, "\tPID: " + thread.getThreadId()
            + " | Suspended: " + thread.isSuspended()
            + " | Native: " + thread.isInNative()
            + " | State: " + thread.getThreadState());
    if (thread.getLockedMonitors().length != 0) {
        log.log(Level.SEVERE, "\tThread is waiting on monitor(s):");
        for (MonitorInfo monitor : thread.getLockedMonitors()) {
            log.log(Level.SEVERE, "\t\tLocked on:" + monitor.getLockedStackFrame());
        }
    }
    log.log(Level.SEVERE, "\tStack:");
    //
    for (StackTraceElement stack : thread.getStackTrace()) {
        log.log(Level.SEVERE, "\t\t" + stack);
    }
}
 
Example 3
Source File: LogConsolidated.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
private static void log(Logger logger, Level level, String message, Throwable t) {

//    	java.util.logging.Level l2 = null;
//    	if (level == Level.INFO)
//    		l2 =  java.util.logging.Level.INFO;
//    	else if (level == Level.WARN || level == Level.ERROR)
//    		l2 =  java.util.logging.Level.WARNING;
//    	else if (level == Level.FATAL)
//    		l2 =  java.util.logging.Level.SEVERE;

		if (t == null) {
			logger.log(level, message);

		} else {
			logger.log(level, message, t);
		}

	}
 
Example 4
Source File: HandlerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testLoggingMessageWithBundle() throws Exception {
    FileObject dir  = TimesCollectorPeerTest.makeScratchDir(this);
    
    Logger LOG = Logger.getLogger("TIMER.instance.of.my.object");
    LogRecord rec = new LogRecord(Level.FINE, "LOG_Project"); // NOI18N
    rec.setParameters(new Object[] { dir, dir });
    rec.setResourceBundle(ResourceBundle.getBundle(HandlerTest.class.getName()));
    LOG.log(rec);

    Collection<Object> files = TimesCollectorPeer.getDefault().getFiles();
    assertEquals("One object " + files, 1, files.size());
    
    Description descr = TimesCollectorPeer.getDefault().getDescription(files.iterator().next(), "LOG_Project");
    assertNotNull(descr);
    
    if (descr.getMessage().indexOf("My Project") == -1) {
        fail("Localized msg should contain 'My Project': " + descr.getMessage());
    }
}
 
Example 5
Source File: Logging.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Report where an issue was encountered.
 *
 * @param context the LoadContext containing the resource 
 */
public static void reportSource(final Level lvl, final LoadContext context)
{
	Logger l = getLogger();
	if (l.isLoggable(lvl))
	{
		if (context != null && context.getSourceURI() != null)
		{
			l.log(lvl, " (Source: " + context.getSourceURI() + " )");
		}
		else
		{
			l.log(lvl, " (Source unknown)");
		}
	}
}
 
Example 6
Source File: SuiteCustomizerLibraries.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void refreshPlatforms() {
    Logger logger = Logger.getLogger(SuiteCustomizerLibraries.class.getName());
    NbPlatform plaf = getProperties().getActivePlatform();
    if (plaf == null) { // #186992
        return;
    }
    logger.log(Level.FINE, "refreshPlatforms --> {0}", plaf.getLabel());
    platformValue.setModel(new PlatformComponentFactory.NbPlatformListModel(plaf)); // refresh
    if (getProperties().getEvaluator().getProperty("nbplatform.active") != null) {
        platformValue.requestFocus();
    } else { // custom local platform, typical with #197038
        platform.setEnabled(false);
        platformValue.setEnabled(false);
        managePlafsButton.setEnabled(false);
    }
}
 
Example 7
Source File: MutualExclusionSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean addStack(IOException x, Set<Closeable> unexpectedCounter, Set<Closeable> expectedCounter) {
    try {
        addStack(x, unexpectedCounter);
        addStack(x, expectedCounter);
    } catch (IllegalArgumentException e) { // #233546
        Logger log = Logger.getLogger(MutualExclusionSupport.class.getName());
        String unexpectedStr = unexpectedCounter == null
                ? "null" //NOI18N
                : Arrays.toString(unexpectedCounter.toArray());
        String expectedStr = expectedCounter == null
                ? "null" //NOI18N
                : Arrays.toString(expectedCounter.toArray());
        log.log(Level.WARNING, "Cannot add stack to exception: " //NOI18N
                + "unexpectedCounter: {0}, expectedCounter: {1}", //NOI18N
                new Object[]{unexpectedStr, expectedStr});
        log.log(Level.INFO, null, e);
        log.log(Level.INFO, "Exception x", x); //NOI18N
    }
    return true;
}
 
Example 8
Source File: Metrics.java    From bStats-Metrics with GNU Lesser General Public License v3.0 6 votes vote down vote up
private JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
    JsonObject chart = new JsonObject();
    chart.addProperty("chartId", chartId);
    try {
        JsonObject data = getChartData();
        if (data == null) {
            // If the data is null we don't send the chart.
            return null;
        }
        chart.add("data", data);
    } catch (Throwable t) {
        if (logFailedRequests) {
            logger.log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example 9
Source File: OSPLog.java    From osp with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Shows the log when it is invoked from the event queue.
 */
public static JFrame showLog() {
  if(OSPRuntime.appletMode||(OSPRuntime.applet!=null)) {
    return org.opensourcephysics.controls.MessageFrame.showLog(true);
  }
  getOSPLog().setVisible(true);
  Logger logger = OSPLOG.getLogger();
  for(int i = 0, n = messageStorage.length; i<n; i++) {
    LogRecord record = messageStorage[(i+messageIndex)%n];
    if(record!=null) {
      logger.log(record);
    }
  }
  messageIndex = 0;
  return getOSPLog();
}
 
Example 10
Source File: AbstractRefactoring.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Collects and returns a set of refactoring elements - objects that
 * will be affected by the refactoring.
 * @param session RefactoringSession that the operation will use to return
 * instances of {@link org.netbeans.modules.refactoring.api.RefactoringElement} class representing objects that
 * will be affected by the refactoring.
 * @return Chain of problems encountered or <code>null</code> in no problems
 * were found.
 */
@CheckForNull
public final Problem prepare(@NonNull RefactoringSession session) {
    try {
        Parameters.notNull("session", session); // NOI18N
        long time = System.currentTimeMillis();

        Problem p = null;
        boolean checkCalled = false;
        if (currentState < PARAMETERS_CHECK) {
            p = checkParameters();
            checkCalled = true;
        }
        if (p != null && p.isFatal()) {
            return p;
        }

        p = pluginsPrepare(checkCalled ? p : null, session);
        Logger timer = Logger.getLogger("TIMER.RefactoringPrepare");
        if (timer.isLoggable(Level.FINE)) {
            time = System.currentTimeMillis() - time;
            timer.log(Level.FINE, "refactoring.prepare", new Object[]{this, time});
        }
        return p;
    } finally {
        session.finished();
    }
}
 
Example 11
Source File: Logging.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Beep and print error message if PCGen is debugging.
 *
 * @param s String error message
 */
public static void errorPrint(final String s)
{
	Logger l = getLogger();
	if (l.isLoggable(ERROR))
	{
		l.log(ERROR, s);
	}
}
 
Example 12
Source File: EventBus.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void handleException(Throwable exception, SubscriberExceptionContext context) {
  Logger logger = logger(context);
  if (logger.isLoggable(Level.SEVERE)) {
    logger.log(Level.SEVERE, message(context), exception);
  }
}
 
Example 13
Source File: BirtTimer.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * writes "{0} takes {1} Milliseconds." to log  
 * 
 * @param logger a Java logger object
 * @param level log level
 * @param operationName the operation name
 */
public void logTimeTaken(Logger logger, Level level, String operationName) {
	if (logger.isLoggable(level))
	{
		logger.log(level, "{0} takes {1} Milliseconds.",	// $NON-NLS-1$ 
				new String[] {operationName, new Integer(delta()).toString()} );
	}
}
 
Example 14
Source File: WatchdogThread.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
private static void dumpThread(ThreadInfo thread, Logger log, Level level)
{
    if (thread == null) return;
    if ( thread.getThreadState() != State.WAITING )
    {
        log.log( level, "------------------------------" );
        //
        log.log( level, "Current Thread: " + thread.getThreadName() );
        log.log( level, "\tPID: " + thread.getThreadId()
                + " | Suspended: " + thread.isSuspended()
                + " | Native: " + thread.isInNative()
                + " | State: " + thread.getThreadState() 
                + " | Blocked Time: " + thread.getBlockedTime()     // Cauldron add info about blocked time
                + " | Blocked Count: " + thread.getBlockedCount()); // Cauldron add info about blocked count
        
        if ( thread.getLockedMonitors().length != 0 )
        {
            log.log( level, "\tThread is waiting on monitor(s):" );
            for ( MonitorInfo monitor : thread.getLockedMonitors() )
            {
                log.log( level, "\t\tLocked on:" + monitor.getLockedStackFrame() );
            }
        }
        if ( thread.getLockOwnerId() != -1 ) log.log( level, "\tLock Owner Id: " + thread.getLockOwnerId()); // Cauldron + add info about lock owner thread id
        log.log( level, "\tStack:" );
        //
        StackTraceElement[] stack = thread.getStackTrace();
        for ( int line = 0; line < stack.length; line++ )
        {
            log.log( level, "\t\t" + stack[line].toString() );
        }
    }
}
 
Example 15
Source File: Client.java    From cache2k with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link Client} that will auto connect to a {@link Server}
 * on the specified port.
 *
 * @param address the {@link InetAddress} on which the {@link Server}
 *                is accepting requests
 * @param port    the port on which the {@link Server} is
 *                is accepting requests
 * @throws IOException when the {@link Client} can't connect to the
 *                     {@link Server}
 */
public Client(InetAddress address, int port) throws IOException {
  Logger logger = Logger.getLogger(this.getClass().getName());
  this.port = port;
  try {
      logger.log(Level.INFO, "Starting " + this.getClass().getCanonicalName() +
              " client connecting to server at address:" + address + " port:" + port);
      this.socket = new Socket(address, port);
  } catch (IOException ioe) {
      throw new IOException("Client failed to connect to server at " + address + ":" + port, ioe);
  }
  this.oos = new ObjectOutputStream(socket.getOutputStream());
  this.ois = new ObjectInputStream(socket.getInputStream());
}
 
Example 16
Source File: TestWBConfigurationFactory.java    From cms with Apache License 2.0 5 votes vote down vote up
@Test
public void test_getConfiguration_no_config()
{
	Logger loggerMock = EasyMock.createMock(Logger.class);
	Whitebox.setInternalState(CmsConfigurationFactory.class, "configPath", "META-INF/wbconfiguration2.xml");
	Whitebox.setInternalState(CmsConfigurationFactory.class, "log", loggerMock);
	loggerMock.log(EasyMock.anyObject(Level.class), EasyMock.anyObject(String.class), EasyMock.anyObject(Exception.class));
	EasyMock.replay(loggerMock);
	CmsConfiguration config1 = CmsConfigurationFactory.getConfiguration();
	assertTrue(config1 == null);
}
 
Example 17
Source File: TestLoggerBundleSync.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {
    try {
        handler.setLevel(Level.FINEST);
        while (goOn) {
            Logger l;
            Logger foo = Logger.getLogger("foo");
            Logger bar = Logger.getLogger("foo.bar");
            for (long i=0; i < nextLong.longValue() + 100 ; i++) {
                if (!goOn) break;
                l = Logger.getLogger("foo.bar.l"+i);
                final ResourceBundle b = l.getResourceBundle();
                final String name = l.getResourceBundleName();
                if (b != null) {
                    if (!name.equals(b.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +b.getBaseBundleName());
                    }
                }
                Logger ll = Logger.getLogger(l.getName()+".bie.bye");
                ResourceBundle hrb;
                String hrbName;
                if (handler.getLevel() != Level.FINEST) {
                    throw new RuntimeException("Handler level is not finest: "
                            + handler.getLevel());
                }
                final int countBefore = handler.count;
                handler.reset();
                ll.setLevel(Level.FINEST);
                ll.addHandler(handler);
                ll.log(Level.FINE, "dummy {0}", this);
                ll.removeHandler(handler);
                final int countAfter = handler.count;
                if (countBefore == countAfter) {
                    throw new RuntimeException("Handler not called for "
                            + ll.getName() + "("+ countAfter +")");
                }
                hrb = handler.rb;
                hrbName = handler.rbName;
                if (name != null) {
                    // if name is not null, then it implies that it
                    // won't change, since setResourceBundle() cannot
                    // replace a non null name.
                    // Since we never set the resource bundle on 'll',
                    // then ll must inherit its resource bundle [name]
                    // from l - and therefor we should find it in
                    // handler.rb/handler.rbName
                    if (!name.equals(hrbName)) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrbName);
                    }
                    // here we know that hrbName is not null so hrb
                    // should not be null either.
                    if (!name.equals(hrb.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrb.getBaseBundleName());
                    }
                }

                // Make sure to refer to 'l' explicitly in order to
                // prevent eager garbage collecting before the end of
                // the test (JDK-8030192)
                if (!ll.getName().startsWith(l.getName())) {
                    throw new RuntimeException("Logger " + ll.getName()
                            + "does not start with expected prefix "
                            + l.getName());
                }

                getRBcount.incrementAndGet();
                if (!goOn) break;
                Thread.sleep(1);
            }
        }
   } catch (Exception x) {
       fail(x);
   }
}
 
Example 18
Source File: TestLoggerBundleSync.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {
    try {
        handler.setLevel(Level.FINEST);
        while (goOn) {
            Logger l;
            Logger foo = Logger.getLogger("foo");
            Logger bar = Logger.getLogger("foo.bar");
            for (long i=0; i < nextLong.longValue() + 100 ; i++) {
                if (!goOn) break;
                l = Logger.getLogger("foo.bar.l"+i);
                final ResourceBundle b = l.getResourceBundle();
                final String name = l.getResourceBundleName();
                if (b != null) {
                    if (!name.equals(b.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +b.getBaseBundleName());
                    }
                }
                Logger ll = Logger.getLogger(l.getName()+".bie.bye");
                ResourceBundle hrb;
                String hrbName;
                if (handler.getLevel() != Level.FINEST) {
                    throw new RuntimeException("Handler level is not finest: "
                            + handler.getLevel());
                }
                final int countBefore = handler.count;
                handler.reset();
                ll.setLevel(Level.FINEST);
                ll.addHandler(handler);
                ll.log(Level.FINE, "dummy {0}", this);
                ll.removeHandler(handler);
                final int countAfter = handler.count;
                if (countBefore == countAfter) {
                    throw new RuntimeException("Handler not called for "
                            + ll.getName() + "("+ countAfter +")");
                }
                hrb = handler.rb;
                hrbName = handler.rbName;
                if (name != null) {
                    // if name is not null, then it implies that it
                    // won't change, since setResourceBundle() cannot
                    // replace a non null name.
                    // Since we never set the resource bundle on 'll',
                    // then ll must inherit its resource bundle [name]
                    // from l - and therefor we should find it in
                    // handler.rb/handler.rbName
                    if (!name.equals(hrbName)) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrbName);
                    }
                    // here we know that hrbName is not null so hrb
                    // should not be null either.
                    if (!name.equals(hrb.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrb.getBaseBundleName());
                    }
                }

                // Make sure to refer to 'l' explicitly in order to
                // prevent eager garbage collecting before the end of
                // the test (JDK-8030192)
                if (!ll.getName().startsWith(l.getName())) {
                    throw new RuntimeException("Logger " + ll.getName()
                            + "does not start with expected prefix "
                            + l.getName());
                }

                getRBcount.incrementAndGet();
                if (!goOn) break;
                Thread.sleep(1);
            }
        }
   } catch (Exception x) {
       fail(x);
   }
}
 
Example 19
Source File: TestLoggerBundleSync.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void run() {
    try {
        handler.setLevel(Level.FINEST);
        while (goOn) {
            Logger l;
            Logger foo = Logger.getLogger("foo");
            Logger bar = Logger.getLogger("foo.bar");
            for (long i=0; i < nextLong.longValue() + 100 ; i++) {
                if (!goOn) break;
                l = Logger.getLogger("foo.bar.l"+i);
                final ResourceBundle b = l.getResourceBundle();
                final String name = l.getResourceBundleName();
                if (b != null) {
                    if (!name.equals(b.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +b.getBaseBundleName());
                    }
                }
                Logger ll = Logger.getLogger(l.getName()+".bie.bye");
                ResourceBundle hrb;
                String hrbName;
                if (handler.getLevel() != Level.FINEST) {
                    throw new RuntimeException("Handler level is not finest: "
                            + handler.getLevel());
                }
                final int countBefore = handler.count;
                handler.reset();
                ll.setLevel(Level.FINEST);
                ll.addHandler(handler);
                ll.log(Level.FINE, "dummy {0}", this);
                ll.removeHandler(handler);
                final int countAfter = handler.count;
                if (countBefore == countAfter) {
                    throw new RuntimeException("Handler not called for "
                            + ll.getName() + "("+ countAfter +")");
                }
                hrb = handler.rb;
                hrbName = handler.rbName;
                if (name != null) {
                    // if name is not null, then it implies that it
                    // won't change, since setResourceBundle() cannot
                    // replace a non null name.
                    // Since we never set the resource bundle on 'll',
                    // then ll must inherit its resource bundle [name]
                    // from l - and therefor we should find it in
                    // handler.rb/handler.rbName
                    if (!name.equals(hrbName)) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrbName);
                    }
                    // here we know that hrbName is not null so hrb
                    // should not be null either.
                    if (!name.equals(hrb.getBaseBundleName())) {
                        throw new RuntimeException("Unexpected bundle name: "
                                +hrb.getBaseBundleName());
                    }
                }

                // Make sure to refer to 'l' explicitly in order to
                // prevent eager garbage collecting before the end of
                // the test (JDK-8030192)
                if (!ll.getName().startsWith(l.getName())) {
                    throw new RuntimeException("Logger " + ll.getName()
                            + "does not start with expected prefix "
                            + l.getName());
                }

                getRBcount.incrementAndGet();
                if (!goOn) break;
                Thread.sleep(1);
            }
        }
   } catch (Exception x) {
       fail(x);
   }
}
 
Example 20
Source File: ChildProcess.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    @SuppressWarnings("resource")
    Scanner input = new Scanner(System.in);
    Logger log = Logger.getLogger(ChildProcess.class.getName());
    log.log(Level.INFO, input.nextLine());
}