Java Code Examples for java.util.logging.Logger

The following are top voted examples for showing how to use java.util.logging.Logger. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: aws-toolkit-eclipse   File: EmailMessageLauncher.java View source code 6 votes vote down vote up
/**
 * Use "mailto:" link to open an email message via the system preferred
 * email client.
 */
public void open() {
    try {

        StringBuilder mailto = new StringBuilder()
            .append("mailto:").append(HttpUtils.urlEncode(recipient, false))
            .append("?subject=").append(HttpUtils.urlEncode(subject, false))
            .append("&body=").append(HttpUtils.urlEncode(body, false));

        Program.launch(mailto.toString());

    } catch (Exception e) {
        Logger logger = Logger.getLogger(EmailMessageLauncher.class.getName());

        logger.warning("Unable to open email message to '" + recipient + "': " + e.getMessage());
    }
}
 
Example 2
Project: netlib   File: BufferedLogger.java View source code 6 votes vote down vote up
/**
 * Directly log msg.
 * 
 * @param logger
 * @param level
 * @param msg
 * @param withStackTrace    true=log inclused current stack trace
 */
public void logLine(Logger logger, Level level, String msg, boolean withStackTrace) {
    String finalMsg = logMessagePrefix+msg;
    if (withStackTrace) {
        logger.log(level, finalMsg, new Throwable());
    } else {
        logger.log(level, finalMsg);
    }
}
 
Example 3
Project: fiji   File: JavaCompiler.java View source code 6 votes vote down vote up
public static void enableLogging() {
    Logger logger = Logger.getLogger(com.sun.tools.javac.Main.class.getPackage().getName());
    logger.setLevel(Level.ALL);
    for (Handler h : logger.getParent().getHandlers()) {
        h.setLevel(Level.ALL);
   }

}
 
Example 4
Project: nmonvisualizer   File: LogViewerDialog.java View source code 6 votes vote down vote up
private void configureLogging() {
    Logger root = Logger.getLogger("");

    levels.setSelectedItem(root.getLevel());

    // remove all existing handlers and add one that logs to this class
    for (Handler handler : root.getHandlers()) {
        root.removeHandler(handler);
    }

    root.addHandler(new LogHandler());
}
 
Example 5
Project: netlib   File: ByteArrayTestUtil.java View source code 6 votes vote down vote up
/**
 * Read expectedResponse.length number of bytes from responseIS and compare it with the expectedResponse.
 * 
 * @param log     if null: do not log
 * @param msg
 * @param expectedResponse
 * @param actualResponseIS
 * @throws IOException
 */
public static void assertByteArrayFromInputStream(Logger log, String msg, byte[] expectedResponse, InputStream actualResponseIS) throws IOException {
    // read the expected number of bytes
    byte[] response = new byte[expectedResponse.length];
    int expLen = expectedResponse.length;
    for (int i=0; i<expLen; i++) {
        response[i] = (byte)actualResponseIS.read();
        if (log!=null) {
            log.info("  read response["+i+"/"+(expLen-1)+"]="+
                    response[i]         + "('"+ByteArrayUtil.asChar(response[i])+"') , expected: " + 
                    expectedResponse[i] + "('"+ByteArrayUtil.asChar(expectedResponse[i])+"')");
        }
    }

    ByteArrayTestUtil.assertEquals("wrong response", expectedResponse, response);
}
 
Example 6
Project: SOLR   File: LogLevelSelection.java View source code 6 votes vote down vote up
private Level getEffectiveLevel(Logger logger) {
  Level level = logger.getLevel();
  if (level != null) {
    return level;
  }
  for (Level l : LEVELS) {
    if (l == null) {
      // avoid NPE
      continue;
    }
    if (logger.isLoggable(l)) {
      // return first level loggable
      return l;
    }
  }
  return Level.OFF;
}
 
Example 7
Project: fiji   File: ToolProvider.java View source code 6 votes vote down vote up
static <T> T trace(Level level, Object reason) {
    // NOTE: do not make this method private as it affects stack traces
    try {
        if (System.getProperty(propertyName) != null) {
            StackTraceElement[] st = Thread.currentThread().getStackTrace();
            String method = "???";
            String cls = ToolProvider.class.getName();
            if (st.length > 2) {
                StackTraceElement frame = st[2];
                method = String.format((Locale)null, "%s(%s:%s)",
                                       frame.getMethodName(),
                                       frame.getFileName(),
                                       frame.getLineNumber());
                cls = frame.getClassName();
            }
            Logger logger = Logger.getLogger(loggerName);
            if (reason instanceof Throwable) {
                logger.logp(level, cls, method,
                            reason.getClass().getName(), (Throwable)reason);
            } else {
                logger.logp(level, cls, method, String.valueOf(reason));
            }
        }
    } catch (SecurityException ex) {
        System.err.format((Locale)null, "%s: %s; %s%n",
                          ToolProvider.class.getName(),
                          reason,
                          ex.getLocalizedMessage());
    }
    return null;
}
 
Example 8
Project: appengine-java-vm-runtime   File: LoggingServlet.java View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
  resp.setContentType("text/plain");
  if (req.getParameter("printLogs") != null) {
    LogService ls = LogServiceFactory.getLogService();
    LogQuery query = withIncludeAppLogs(true).minLogLevel(LogService.LogLevel.FATAL);
    for (RequestLogs logs : ls.fetch(query)) {
      for (AppLogLine logLine : logs.getAppLogLines()) {
        if (logLine.getLogLevel().equals(LogService.LogLevel.FATAL)) {
          resp.getWriter().println(logLine);
        }
      }
    }
  } else {
    Logger logger = Logger.getLogger("com.foo");
    resp.getWriter().println(logger.getLevel());
    Logger logger2 = Logger.getLogger("com.foo.bar");
    resp.getWriter().println(logger2.getLevel());
    resp.getWriter().println(configRan);
    logger2.severe("not null");
    logger2.severe((String)null);
  }
}
 
Example 9
Project: freemind-mmx   File: TileImage.java View source code 6 votes vote down vote up
/**
 * @param pDimension
 * @param pX
 * @param pY
 * @param pZoom
 * @param mTileController
 * @param pLogger
 * @param pDy
 * @param pDx
 */
public void setTiles(int pDimension, int pX, int pY, int pZoom,
		TileController mTileController, Logger pLogger, int pDx, int pDy) {
	mDx = pDx;
	mDy = pDy;
	mTiles = new Tile[pDimension][pDimension];
	for (int i = 0; i < pDimension; ++i) {
		for (int j = 0; j < pDimension; ++j) {
			pLogger.fine("Trying to load tile to x=" + (pX + i)
					+ ", y=" + (pY + j) + ", zoom=" + pZoom);
			mTiles[i][j] = mTileController.getTile(pX + i, pY + j,
					pZoom);
		}
	}
	mTilesPresent = true;
}
 
Example 10
Project: shrinkwrap   File: DynamicContainerTestBase.java View source code 6 votes vote down vote up
/**
 * SHRINKWRAP-275
 */
@Test
@ArchiveType(ResourceContainer.class)
public void testAddResourceStringTargetResourceFromJar() throws Exception {
    // Causing NPE
    getResourceContainer().addAsResource("java/lang/String.class", "String.class");

    ArchivePath testPath = new BasicPath(getResourcePath(), "String.class");
    Assert.assertTrue("Archive should contain " + testPath, getArchive().contains(testPath));
    Logger.getAnonymousLogger().info(getArchive().toString(true));
}
 
Example 11
Project: SPINdle   File: AppLoggerImpl.java View source code 6 votes vote down vote up
private static final Logger generateLogger(File file) throws SecurityException, IOException {
	if (null == file) file = new File(logFolder, "dummy_" + Utilities.getRandomString(DomConst.LOG_FILE_ID_LENGTH));
	File logFolderF = file.getParentFile();
	if (!logFolderF.exists()) logFolderF.mkdirs();

	Logger logger = Logger.getLogger(file.toString());
	logger.setUseParentHandlers(false);

	FileHandler fileHandler = new FileHandler(file.getCanonicalPath());
	fileHandler.setFormatter(new LogFormatter());
	logger.addHandler(fileHandler);

	return logger;
}
 
Example 12
Project: resin   File: EnvironmentLogger.java View source code 6 votes vote down vote up
/**
 * Sets a custom logger if possible
 */
boolean addCustomLogger(Logger logger)
{
  if (logger.getClass().getName().startsWith("java"))
    return false;
  
  Logger oldLogger = _localLoggers.get();

  if (oldLogger != null)
    return false;

  _localLoggers.set(logger);
  
  if (_parent != null) {
    logger.setParent(_parent);
  }

  return true;
}
 
Example 13
Project: funambol-client-sdk   File: TimeUtils.java View source code 6 votes vote down vote up
/**
 * Set a string date from UTC format (yyyyMMdd'T'HHmmss'Z') into
 * a format dd/MM/yyyy HH:mm:ss according to default local timezone.
 *
 * @param UTCFormat the input date in UTC format
 * @return actualTime the date into default local timezone
 */
public static String UTCToLocalTime(String UTCFormat, Logger logger) {

    String actualTime = UTCFormat;
    try {
        SimpleDateFormat formatter = new SimpleDateFormat(PATTERN_UTC);
        formatter.setLenient(false);
        formatter.setTimeZone(TIMEZONE_UTC);
        Date date = formatter.parse(UTCFormat);
        Calendar rightNow = Calendar.getInstance();
        formatter.setCalendar(rightNow);
        formatter.applyPattern(PATTERN_LOCALTIME);
        actualTime = formatter.format(date);

    } catch (Exception e) {
        if (logger != null) {
            logger.severe("Error into convertion from UTC to Local time");
            logger.throwing("TimeUtils", "UTCToLocalTime", e);
        }
    }
    return actualTime;

}
 
Example 14
Project: SOLR   File: LogLevelSelection.java View source code 6 votes vote down vote up
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
        throws IOException, ServletException {
  if (request.getParameter("submit").equals("set")) {

    Map paramMap = request.getParameterMap();

    Iterator iParams = paramMap.entrySet().iterator();
    while (iParams.hasNext()) {
      Map.Entry p = (Map.Entry) iParams.next();
      String name = (String) p.getKey();
      String value = ((String[]) p.getValue())[0];

      if (name.equals("submit")) continue;
      Logger logger;
      LogManager logManager = LogManager.getLogManager();
      if ("root".equals(name)) {
        logger = logManager.getLogger("");
      } else logger = logManager.getLogger(name);

      if ("unset".equals(value)) {
        if ((logger != null) && (logger.getLevel() != null)) {
          logger.setLevel(null);
          log.info("Unset log level on '" + name + "'.");
        }
      } else {
        Level level = Level.parse(value);
        if (logger == null) logger = Logger.getLogger(name);
        if (logger.getLevel() != level) {
          logger.setLevel(level);
          log.info("Set '" + name + "' to " +
                  level + " level.");
        }
      }
    }
  } else {
    log.fine("Selection form cancelled");
  }

  // Redirect back to standard get page.
  response.sendRedirect(request.getRequestURI());
}
 
Example 15
Project: jade_agents   File: JavaLoggingLogManagerImpl.java View source code 6 votes vote down vote up
public void setLogLevel(String name, int level){
	
	//update the LogInfo associated.
	for(int i=0; i<this.loggers.size(); i++){
		LoggerInfo lInfo = (LoggerInfo)this.loggers.get(i);
		if(lInfo.getName().equalsIgnoreCase(name)){
			lInfo.setLevel(level);
			break;
		}
	}	
	if(name.equals(DEFAULT_ROOT_LOGGER_NAME)) {
		name = "";
	}
	
	Logger logger = logManager.getLogger(name);
	Level  newLoggerLevel = Level.INFO;
	if(level == Level.ALL.intValue()){
		newLoggerLevel = Level.ALL;
	}else if(level == Level.SEVERE.intValue()){
		newLoggerLevel = Level.SEVERE;
	}else if(level == Level.WARNING.intValue()){
		newLoggerLevel = Level.WARNING;
	}else if(level == Level.INFO.intValue()){
		newLoggerLevel = Level.INFO;
	}else if(level == Level.CONFIG.intValue()){
		newLoggerLevel = Level.CONFIG;
	}else if(level == Level.FINE.intValue()){
		newLoggerLevel = Level.FINE;
	}else if(level == Level.FINER.intValue()){
		newLoggerLevel = Level.FINER;
	}else if(level == Level.FINEST.intValue()){
		newLoggerLevel = Level.FINEST;
	}else if(level == Level.OFF.intValue()){
		newLoggerLevel = Level.OFF;
	}
	logger.setLevel(newLoggerLevel);
	//Set level for handlers associated to logger
	if (logger.getParent() != null) {
		Handler[] pHandlers = logger.getParent().getHandlers();
		for (int i=0; i<pHandlers.length; i++){
			pHandlers[i].setLevel(newLoggerLevel);
		}
	}
	Handler[] handlers = logger.getHandlers();
	for (int j=0; j<handlers.length; j++){
		handlers[j].setLevel(newLoggerLevel);
	}
}
 
Example 16
Project: resin   File: QuercusProgram.java View source code 6 votes vote down vote up
public boolean logModified(Logger log)
{
  if (isModified()) {
    log.finer(_sourceFile + " is modified");

    return true;
  }
  else
    return false;
}
 
Example 17
Project: google-web-toolkit-svnmirror   File: DevModeLoggingFixes.java View source code 6 votes vote down vote up
/**
 * Replaces all logger.getName() calls, removing a thread specific prefix
 * which is appended to all logger names in dev mode in order to maintain
 * a pseudo tree of loggers for each thread.
 */
public static String getName(Logger logger) {
  if (logger.getName() != null) {
    return removeLoggerPrefix(logger.getName());
  }
  return null;
}
 
Example 18
Project: commons-old   File: RootLogConfigTest.java View source code 6 votes vote down vote up
private void assertNoVerboseLogging(Logger logger) {
  logger.config("Config");
  logger.fine("Fine");
  logger.finer("Finer");
  logger.finest("Finest");
  assertHasNotLoggedToStderr();
  assertHasNotLoggedToFile();
}
 
Example 19
Project: open-mika   File: LoggerTest.java View source code 6 votes vote down vote up
public void testEntering_StringString_Null() {
    Logger child = new MockLogger("childLogger", null);
    Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2);
    child.addHandler(new MockHandler());
    child.setParent(parent);

    child.setLevel(Level.FINER);
    child.entering(null, null);
    LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop();
    assertTrue(CallVerificationStack.getInstance().empty());
    assertSame(r.getLoggerName(), child.getName());
    assertEquals(r.getMessage(), "ENTRY");
    assertSame(r.getResourceBundleName(), parent.getResourceBundleName());
    assertSame(r.getResourceBundle(), parent.getResourceBundle());
    assertSame(r.getSourceClassName(), null);
    assertSame(r.getSourceMethodName(), null);
    assertSame(r.getLevel(), Level.FINER);
    assertSame(r.getParameters(), null);
    assertSame(r.getThrown(), null);
}
 
Example 20
Project: commons-old   File: LogConfig.java View source code 6 votes vote down vote up
private void maybeAdjustHandlerLevels(Logger logger, Level newLevel) {
  do {
    for (Handler handler : logger.getHandlers()) {
      Level handlerLevel = handler.getLevel();
      if (newLevel.intValue() < handlerLevel.intValue()) {
        handler.setLevel(newLevel);
      }
    }
  } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}
 
Example 21
Project: appengine-java-vm-runtime   File: LogServlet.java View source code 6 votes vote down vote up
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
  String message = req.getParameter("message");
  String context = req.getParameter("context");
  String levelName = req.getParameter("level");
  boolean exception = req.getParameter("exception") != null;

  String dest = req.getParameter("dest");
  if (dest.equals("stdout")) {
    System.out.println(message);
  } else if (dest.equals("stderr")) {
    System.err.println(message);
  } else if (dest.equals("logger")) {
    String multiply = req.getParameter("multiply");
    int multiplyCount = 1;
    if (multiply != null) {
      multiplyCount = Integer.parseInt(multiply);
    }
    // Optionally print the same message a large number of times (for testing large logs).
    for (int i = 0; i < multiplyCount; i++) {
      Logger log = Logger.getLogger(context);
      Level level = (levelName == null) ? Level.INFO : Level.parse(levelName);
      if (exception) {
        Logger.getLogger(context).log(level, message, new Exception(message));
      } else {
        Logger.getLogger(context).log(level, message);
      }
    }
  } else if (dest.equals("servlet")) {
    if (exception) {
      getServletContext().log(message, new Exception(message));
    } else {
      getServletContext().log(message);
    }
  } else if (dest.equals("global")) {
    // Logger.global should not be null anymore
    Logger.global.log(Level.INFO, message);
  } else {
    throw new ServletException("unknown destination: " + dest);
  }
}
 
Example 22
Project: open-mika   File: LoggerTest.java View source code 6 votes vote down vote up
public void testExiting_StringString_Null() {
    Logger child = new MockLogger("childLogger", null);
    Logger parent = new MockLogger("parentLogger", VALID_RESOURCE_BUNDLE2);
    child.addHandler(new MockHandler());
    child.setParent(parent);

    child.setLevel(Level.FINER);
    child.exiting(null, null);
    LogRecord r = (LogRecord) CallVerificationStack.getInstance().pop();
    assertTrue(CallVerificationStack.getInstance().empty());
    assertSame(r.getLoggerName(), child.getName());
    assertEquals(r.getMessage(), "RETURN");
    assertSame(r.getResourceBundleName(), parent.getResourceBundleName());
    assertSame(r.getResourceBundle(), parent.getResourceBundle());
    assertSame(r.getSourceClassName(), null);
    assertSame(r.getSourceMethodName(), null);
    assertSame(r.getLevel(), Level.FINER);
    assertSame(r.getParameters(), null);
    assertSame(r.getThrown(), null);
}
 
Example 23
Project: carbon-deployment   File: TomEEMyFacesContainerInitializer.java View source code 5 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext ctx) throws ServletException {
	// try to skip first
	if ("true".equalsIgnoreCase(ctx.getInitParameter("org.apache.myfaces.INITIALIZE_ALWAYS_STANDALONE"))
	    || "true".equals(SystemInstance.get().getProperty(OPENEJB_JSF_SKIP, "false"))) {
		return;
	}

	// if mojarra is present skip myfaces startup
	try {
		ctx.getClassLoader().loadClass("com.sun.faces.context.SessionMap");
		return;
	} catch (final ClassNotFoundException cnfe) {
		// no-op
	} catch (final NoClassDefFoundError error) {
		// no-op
	}

	// some message filtering, not a perf killer since this class don't log a lot
	final Logger abstractInitializerLogger = Logger.getLogger(AbstractFacesInitializer.class.getName());
	abstractInitializerLogger.setFilter(new RemoveLogMessage(
			new RemoveLogMessage(abstractInitializerLogger.getFilter(),
			                     Level.WARNING, "No mappings of FacesServlet found. Abort initializing MyFaces."),
			Level.WARNING, "No mappings of FacesServlet found. Abort destroy MyFaces."));

	if ((classes != null && !classes.isEmpty()) || isFacesServletPresent(ctx) || isFacesConfigPresent(ctx)) {
		// we found a faces-config.xml or some classes so let's delegate to myfaces

		// since we don't want to call isFacesConfigPresent again (it scan all jars!!!!)
		// forcing classes to not be empty
		Set<Class<?>> passedClasses = classes;
		if (passedClasses == null) {
			passedClasses = new HashSet<Class<?>>();
		}
		if (passedClasses.isEmpty()) {
			passedClasses.add(TomEEMyFacesContainerInitializer.class);
		}

		if (ctx instanceof ApplicationContextFacade) {
			try {
				final ApplicationContext appCtx = (ApplicationContext) get(ApplicationContextFacade.class, ctx);
				final Context tomcatCtx = (Context) get(ApplicationContext.class, appCtx);
				if (!Arrays.asList(tomcatCtx.findApplicationListeners()).contains(StartupServletContextListener.class.getName())) {
					addListener(ctx);
				}
			} catch (final Exception e) {
				// add it, not important we'll simply get a warning saying it is already here
				addListener(ctx);
			}
		}

		// finally delegating begin sure we'll not call isFacesConfigPresent
		delegate.onStartup(classes, ctx);
	}
}