Java Code Examples for java.util.logging.Level#FINER

The following examples show how to use java.util.logging.Level#FINER . 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: PLogger.java    From uavstack with Apache License 2.0 6 votes vote down vote up
private static String getLogLevelStr(Level level) {

        if (level == Level.INFO) {
            return "I ";
        }
        else if (level == Level.SEVERE) {
            return "E ";
        }
        else if (level == Level.WARNING) {
            return "W ";
        }
        else if (level == Level.FINEST) {
            return "D ";
        }
        else if (level == Level.FINE) {
            return "F ";
        }
        else if (level == Level.FINER) {
            return "FR";
        }
        else {
            return "I ";
        }
    }
 
Example 2
Source File: UIHandlerTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testPublish() {
    
    MyAction a = new MyAction();
    a.putValue(Action.NAME, "Tmp &Action");
    JButton b = new JButton(a);
    
    LogRecord rec = new LogRecord(Level.FINER, "UI_ACTION_BUTTON_PRESS"); // NOI18N
    rec.setParameters(new Object[] { 
        b, 
        b.getClass().getName(), 
        a, 
        a.getClass().getName(), 
        a.getValue(Action.NAME) }
    );
    UILOG.log(rec);        
    
    List<LogRecord> logs = InstallerTest.getLogs();
    assertEquals("One log: " + logs, 1, logs.size());
    LogRecord first = logs.get(0);
    
    assertEquals("This is the logged record", rec.getMessage(), first.getMessage());
    
    
}
 
Example 3
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Parses the command line arguments and executes PMD.
 * @param args command line arguments
 * @return the exit code, where <code>0</code> means successful execution, <code>1</code> means error,
 * <code>4</code> means there have been violations found.
 */
public static int run(String[] args) {
    int status = 0;
    long start = System.nanoTime();
    final PMDParameters params = PMDCommandLineInterface.extractParameters(new PMDParameters(), args, "pmd");
    final PMDConfiguration configuration = PMDParameters.transformParametersIntoConfiguration(params);

    final Level logLevel = params.isDebug() ? Level.FINER : Level.INFO;
    final Handler logHandler = new ConsoleLogHandler();
    final ScopedLogHandlersManager logHandlerManager = new ScopedLogHandlersManager(logLevel, logHandler);
    final Level oldLogLevel = LOG.getLevel();
    LOG.setLevel(logLevel); // Need to do this, since the static logger has
                            // already been initialized at this point
    try {
        int violations = Main.doPMD(configuration);
        if (violations > 0 && configuration.isFailOnViolation()) {
            status = PMDCommandLineInterface.VIOLATIONS_FOUND;
        } else {
            status = 0;
        }
    } catch (Exception e) {
        System.out.println(PMDCommandLineInterface.buildUsageText());
        System.out.println();
        System.err.println(e.getMessage());
        status = PMDCommandLineInterface.ERROR_STATUS;
    } finally {
        logHandlerManager.close();
        LOG.setLevel(oldLogLevel);
        if (params.isBenchmark()) {
            long end = System.nanoTime();
            Benchmarker.mark(Benchmark.TotalPMD, end - start, 0);

            TextReport report = new TextReport(); // TODO get specified
                                                  // report format from
                                                  // config
            report.generate(Benchmarker.values(), System.err);
        }
    }
    return status;
}
 
Example 4
Source File: ProcessUtils.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Simple output-getting command. Cannot be cancelled, and will return null
 * if the external process exits with a non-zero return code.
 *
 * @param command
 *            The command (executable + arguments) to launch
 * @return The process's standard output upon completion
 */
public static @Nullable List<String> getOutputFromCommand(List<String> command) {
    try (TraceCompassLogUtils.ScopeLog sl = new TraceCompassLogUtils.ScopeLog(LOGGER, Level.FINER, "ProcessUtils#getOutputFromComment", "args", command)) { //$NON-NLS-1$ //$NON-NLS-2$
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);

        Process p = builder.start();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charsets.UTF_8));) {
            List<String> output = new LinkedList<>();

            /*
             * We must consume the output before calling Process.waitFor(),
             * or else the buffers might fill and block the external program
             * if there is a lot of output.
             */
            String line = br.readLine();
            while (line != null) {
                output.add(line);
                line = br.readLine();
            }

            int ret = p.waitFor();
            return (ret == 0 ? output : null);
        }
    } catch (IOException | InterruptedException e) {
        return null;
    }
}
 
Example 5
Source File: AbstractDelegatingLogger.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void throwing(final String sourceClass, final String sourceMethod, final Throwable thrown) {
    if (isLoggable(Level.FINER)) {
        final LogRecord lr = new LogRecord(Level.FINER, "THROW");
        lr.setSourceClassName(sourceClass);
        lr.setSourceMethodName(sourceMethod);
        lr.setThrown(thrown);
        doLog(lr);
    }
}
 
Example 6
Source File: AbstractSaslImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected static final void traceOutput(String srcClass, String srcMethod,
    String traceTag, byte[] output, int offset, int len) {
    try {
        int origlen = len;
        Level lev;

        if (!logger.isLoggable(Level.FINEST)) {
            len = Math.min(16, len);
            lev = Level.FINER;
        } else {
            lev = Level.FINEST;
        }

        String content;

        if (output != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream(len);
            new HexDumpEncoder().encodeBuffer(
                new ByteArrayInputStream(output, offset, len), out);
            content = out.toString();
        } else {
            content = "NULL";
        }

        // Message id supplied by caller as part of traceTag
        logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
            new Object[] {traceTag, origlen, content});
    } catch (Exception e) {
        logger.logp(Level.WARNING, srcClass, srcMethod,
            "SASLIMPL09:Error generating trace output: {0}", e);
    }
}
 
Example 7
Source File: ChannelTracer.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
void reportEvent(Event event) {
  Level logLevel;
  switch (event.severity) {
    case CT_ERROR:
      logLevel = Level.FINE;
      break;
    case CT_WARNING:
      logLevel = Level.FINER;
      break;
    default:
      logLevel = Level.FINEST;
  }
  traceOnly(event);
  logOnly(logId, logLevel, event.description);
}
 
Example 8
Source File: AbstractSaslImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected static final void traceOutput(String srcClass, String srcMethod,
    String traceTag, byte[] output, int offset, int len) {
    try {
        int origlen = len;
        Level lev;

        if (!logger.isLoggable(Level.FINEST)) {
            len = Math.min(16, len);
            lev = Level.FINER;
        } else {
            lev = Level.FINEST;
        }

        String content;

        if (output != null) {
            ByteArrayOutputStream out = new ByteArrayOutputStream(len);
            new HexDumpEncoder().encodeBuffer(
                new ByteArrayInputStream(output, offset, len), out);
            content = out.toString();
        } else {
            content = "NULL";
        }

        // Message id supplied by caller as part of traceTag
        logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}",
            new Object[] {traceTag, new Integer(origlen), content});
    } catch (Exception e) {
        logger.logp(Level.WARNING, srcClass, srcMethod,
            "SASLIMPL09:Error generating trace output: {0}", e);
    }
}
 
Example 9
Source File: SimpleConsoleLogger.java    From moleculer-java with MIT License 5 votes vote down vote up
@Override
public void log(LinkedList<LogRecord> records, StringBuilder lines) {
	Throwable cause;
	String msg;
	for (LogRecord record : records) {
		lines.setLength(0);
		final Level l = record.getLevel();
		if (l == Level.SEVERE) {
			lines.append(SEVERE);
		} else if (l == Level.WARNING) {
			lines.append(WARNING);
		} else if (l == Level.INFO) {
			lines.append(INFO);
		} else if (l == Level.CONFIG) {
			lines.append(CONFIG);
		} else if (l == Level.FINE) {
			lines.append(FINE);
		} else if (l == Level.FINER) {
			lines.append(FINER);
		} else {
			lines.append(FINEST);
		}
		msg = record.getMessage();
		if (msg == null) {
			msg = "<null>";
		} else {
			msg = msg.trim();
		}
		System.out.println(lines.append(msg).toString());
		cause = record.getThrown();
		if (cause != null) {
			cause.printStackTrace();
		}
	}
}
 
Example 10
Source File: IdentifiedObjectFinder.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked when an exception occurred during the creation of a candidate from a code.
 */
private static void exceptionOccurred(final FactoryException exception) {
    /*
     * use 'getMessage()' instead of 'getLocalizedMessage()' for
     * giving preference to the locale of system administrator.
     */
    final LogRecord record = new LogRecord(Level.FINER, exception.getMessage());
    record.setLoggerName(Loggers.CRS_FACTORY);
    Logging.log(IdentifiedObjectFinder.class, "find", record);
}
 
Example 11
Source File: ReloadTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
protected @Override Level logLevel() {
    return Level.FINER;
}
 
Example 12
Source File: LinkBartenderSystem.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected Level getLifecycleLogLevel()
{
  return Level.FINER;
}
 
Example 13
Source File: NexusTestBase.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override protected Level logLevel() {
    return Level.FINER;
}
 
Example 14
Source File: TestNGOutputReader.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
     */
    private boolean isValidReportFile(File reportFile) {
        if (!reportFile.canRead()) {
            return false;
        }

        if (reportFile.canRead()) {
            return true;
        }

        long lastModified = reportFile.lastModified();
        long timeDelta = lastModified - timeOfSessionStart;

        final Logger logger = Logger.getLogger("org.netbeans.modules.testng.outputreader.timestamps");//NOI18N
        final Level logLevel = Level.FINER;
        if (logger.isLoggable(logLevel)) {
            logger.log(logLevel, "Report file: " + reportFile.getPath());//NOI18N

            final GregorianCalendar timeStamp = new GregorianCalendar();

            timeStamp.setTimeInMillis(timeOfSessionStart);
            logger.log(logLevel, "Session start:    " + String.format("%1$tT.%2$03d", timeStamp, timeStamp.get(Calendar.MILLISECOND)));//NOI18N

            timeStamp.setTimeInMillis(lastModified);
            logger.log(logLevel, "Report timestamp: " + String.format("%1$tT.%2$03d", timeStamp, timeStamp.get(Calendar.MILLISECOND)));//NOI18N
        }

        if (timeDelta >= 0) {
            return true;
        }

        /*
         * Normally we would return 'false' here, but:
         *
         * We must take into account that modification timestamps of files
         * usually do not hold milliseconds, just seconds. The worst case we
         * must accept is that the session started on YYYY.MM.DD hh:mm:ss.999
         * and the file was saved exactly in the same millisecond but its time
         * stamp is just YYYY.MM.DD hh:mm:ss, i.e 999 milliseconds earlier.
         */
        return -timeDelta <= timeOfSessionStart % 1000;

//        if (timeDelta < -999) {
//            return false;
//        }
//
//        final GregorianCalendar sessStartCal = new GregorianCalendar();
//        sessStartCal.setTimeInMillis(timeOfSessionStart);
//        int sessStartMillis = sessStartCal.get(Calendar.MILLISECOND);
//        if (timeDelta < -sessStartMillis) {
//            return false;
//        }
//
//        final GregorianCalendar fileModCal = new GregorianCalendar();
//        fileModCal.setTimeInMillis(lastModified);
//        if (fileModCal.get(Calendar.MILLISECOND) != 0) {
//            /* So the file's timestamp does hold milliseconds! */
//            return false;
//        }
//
//        /*
//         * Now we know that milliseconds are not part of file's timestamp.
//         * Let's substract the milliseconds part and check whether the delta is
//         * non-negative, now that we only check seconds:
//         */
//        return lastModified >= (timeOfSessionStart - sessStartMillis);
    }
 
Example 15
Source File: GrammaticalLabelFileHandler.java    From grammaticus with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @return Level for label problems that will cause empty or invalid labels to be generated
 */
final Level getLabelWarningLogLevel() {
    return LanguageProviderFactory.get().getBaseLanguage() == parser.getDictionary().getLanguage() ? Level.INFO : Level.FINER;
}
 
Example 16
Source File: GitExpand.java    From skara with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    var flags = List.of(
        Switch.shortcut("")
              .fullname("issues")
              .helptext("Expand issues in the commit message")
              .optional(),
        Switch.shortcut("")
              .fullname("verbose")
              .helptext("Turn on verbose output")
              .optional(),
        Switch.shortcut("")
              .fullname("debug")
              .helptext("Turn on debugging output")
              .optional(),
        Switch.shortcut("")
              .fullname("version")
              .helptext("Print the version of this tool")
              .optional());

    var inputs = List.of(
        Input.position(0)
             .describe("REV")
             .singular()
             .optional()
    );

    var parser = new ArgumentParser("git-publish", flags, inputs);
    var arguments = parser.parse(args);

    if (arguments.contains("version")) {
        System.out.println("git-expand version: " + Version.fromManifest().orElse("unknown"));
        System.exit(0);
    }

    if (arguments.contains("verbose") || arguments.contains("debug")) {
        var level = arguments.contains("debug") ? Level.FINER : Level.FINE;
        Logging.setup(level);
    }

    var cwd = Path.of("").toAbsolutePath();
    var repo = repo(cwd);
    var rev = arguments.at(0).orString("HEAD");
    var commit = lookup(repo, rev);
    var message = commit.message();

    var shouldExpandIssues = getSwitch("issues", arguments, repo);
    if (shouldExpandIssues) {
        var conf = JCheckConfiguration.from(repo, commit.hash());
        if (conf.isPresent()) {
            var project = conf.get().general().jbs();
            var tracker = IssueTracker.from("jira", URI.create("https://bugs.openjdk.java.net"));

            var amended = new ArrayList<String>();
            for (var line : message) {
                var m = ISSUE_ID_PATTERN.matcher(line);
                if (m.matches()) {
                    var id = m.group(2);
                    var issue = tracker.project(project).issue(id);
                    if (issue.isPresent()) {
                        amended.add(id + ": " + issue.get().title());
                    }
                } else {
                    amended.add(line);
                }
            }

            repo.amend(String.join("\n", amended));
        } else {
            System.err.println("warning: could not expand issues commit message,\n" +
                               "         no JBS project configured in .jcheck/conf");
        }
    }
}
 
Example 17
Source File: ClientMainFrame.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Initiate console log and file log
 * 
 * @throws IOException if anything bad happens creating log giles
 */
public void initiateLog() throws IOException {
	Logger mainlogger = Logger.getLogger("");

	for (int i = 0; i < mainlogger.getHandlers().length; i++) {
		mainlogger.removeHandler(mainlogger.getHandlers()[i]);
	}
	if (!nolog) {
		ConsoleHandler consolehandler = new ConsoleHandler();
		consolehandler.setFormatter(new ConsoleFormatter());
		consolehandler.setLevel(Level.ALL);
		consolefilter = new OpenLowcodeLogFilter(Level.FINER, "Console Filter", consolehandler);
		consolehandler.setFilter(consolefilter);
		mainlogger.addHandler(consolehandler);
		File file = new File("./log/");
		if (!file.exists()) {
			boolean result = file.mkdir();
			if (!result)
				throw new RuntimeException("Trying to create log folder " + file.getPath() + ", does not work");
		}
		System.err.println("log folder = " + file.getAbsolutePath());
		FileHandler logfilehandler = new FileHandler("./log/OLcClient%g.log", 10000000, 1000, true);
		logfilefilter = new OpenLowcodeLogFilter(Level.FINER, "Log File Filter", logfilehandler);
		logfilehandler.setFilter(logfilefilter);

		logfilehandler.setLevel(Level.ALL);
		logfilehandler.setFormatter(new FileFormatter(true));
		mainlogger.addHandler(logfilehandler);

		mainlogger.setUseParentHandlers(false);
		
		Logger rootlogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
		for (int i = 0; i < rootlogger.getHandlers().length; i++) {
			rootlogger.removeHandler(rootlogger.getHandlers()[i]);
		}
		rootlogger.addHandler(logfilehandler);
		rootlogger.setLevel(Level.ALL);

		rootlogger.addHandler(consolehandler);
		rootlogger.setUseParentHandlers(false);
	}
}
 
Example 18
Source File: SelfInterpreter.java    From BotLibre with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Evaluate the DEBUG operation.
 * debug ("debug", :0, :2)
 * Log the arguments to the log.
 */
public Vertex evaluateDEBUG(Vertex expression, List<Relationship> arguments, Map<Vertex, Vertex> variables, Network network, long startTime, long maxTime, int stack) {
	StringWriter writer = new StringWriter();
	boolean first = true;
	Level level = null;
	for (Relationship argument : arguments) {
		if (first) {
			first = false;
			if (argument.getTarget().isPrimitive()) {
				// Allow log level to be set as first parameter.
				if (argument.getTarget().is(Primitive.FINEST)) {
					level = Level.FINEST;
					if (!network.getBot().isDebugFine()) {
						return network.createVertex(Primitive.NULL);
					}
				} else if (argument.getTarget().is(Primitive.FINER)) {
					level = Level.FINER;
					if (!network.getBot().isDebugFine()) {
						return network.createVertex(Primitive.NULL);
					}
				} else if (argument.getTarget().is(Primitive.FINE)) {
					level = Level.FINE;
					if (!network.getBot().isDebugFine()) {
						return network.createVertex(Primitive.NULL);
					}
				} else if (argument.getTarget().is(Primitive.INFO)) {
					level = Level.INFO;
				} else if (argument.getTarget().is(Primitive.WARNING)) {
					level = Level.WARNING;
				} else if (argument.getTarget().is(Primitive.SEVERE)) {
					level = Level.SEVERE;
				}
				if (level != null) {
					continue;
				}
				if (!network.getBot().isDebugFine()) {
					return network.createVertex(Primitive.NULL);
				}
			}
		} else{
			writer.write(" : ");
		}
		Vertex value = evaluateExpression(argument.getTarget(), variables, network, startTime, maxTime, stack);
		writer.write(value.printString());
	}
	if (level == null) {
		level = Level.FINE;
	}
	network.getBot().log("DEBUG", writer.toString(), level);
	return network.createVertex(Primitive.NULL);
}
 
Example 19
Source File: BirtEngine.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Gets the birt engine.
 *
 * @param request
 *            the request
 * @param sc
 *            the sc
 *
 * @return the birt engine
 */
public static synchronized IReportEngine getBirtEngine(HttpServletRequest request, ServletContext sc) {
	logger.debug("IN");
	// birtEngine = null;
	if (birtEngine == null) {
		EngineConfig config = new EngineConfig();
		if (configProps != null && !configProps.isEmpty()) {
			String logLevel = configProps.getProperty("logLevel");
			Level level = Level.OFF;
			if ("SEVERE".equalsIgnoreCase(logLevel)) {
				level = Level.SEVERE;
			} else if ("WARNING".equalsIgnoreCase(logLevel)) {
				level = Level.WARNING;
			} else if ("INFO".equalsIgnoreCase(logLevel)) {
				level = Level.INFO;
			} else if ("CONFIG".equalsIgnoreCase(logLevel)) {
				level = Level.CONFIG;
			} else if ("FINE".equalsIgnoreCase(logLevel)) {
				level = Level.FINE;
			} else if ("FINER".equalsIgnoreCase(logLevel)) {
				level = Level.FINER;
			} else if ("FINEST".equalsIgnoreCase(logLevel)) {
				level = Level.FINEST;
			} else if ("ALL".equalsIgnoreCase(logLevel)) {
				level = Level.ALL;
			} else if ("OFF".equalsIgnoreCase(logLevel)) {
				level = Level.OFF;
			}

			String logDir = configProps.getProperty("logDirectory");
			logDir = Utils.resolveSystemProperties(logDir);
			logger.debug("Birt LOG Dir:" + logDir);
			logger.debug("Log config: logDirectory = [" + logDir + "]; level = [" + level + "]");
			config.setLogConfig(logDir, level);
		}

		/*
		 * DefaultResourceLocator drl=new DefaultResourceLocator(); drl.findResource(birtEngine.openReportDesign(arg0), "messages_it_IT.properties",
		 * DefaultResourceLocator.MESSAGE_FILE);
		 */
		// Commented for Birt 3.7 Upgrade see: http://wiki.eclipse.org/Birt_3.7_Migration_Guide#BIRT_3.7_API_Changes
		// config.setEngineHome("");
		IPlatformContext context = new PlatformServletContext(sc);
		config.setPlatformContext(context);
		config.setTempDir(System.getProperty("java.io.tmpdir") + "/birt/");

		// ParameterAccessor.initParameters(sc);
		// config.setResourcePath(ParameterAccessor.getResourceFolder(request));
		// Prepare ScriptLib location
		String scriptLibDir = ParameterAccessor.scriptLibDir;
		ArrayList jarFileList = new ArrayList();
		if (scriptLibDir != null) {
			File dir = new File(scriptLibDir);
			getAllJarFiles(dir, jarFileList);
		}
		String scriptlibClassPath = ""; //$NON-NLS-1$
		for (int i = 0; i < jarFileList.size(); i++)
			scriptlibClassPath += EngineConstants.PROPERTYSEPARATOR + ((File) jarFileList.get(i)).getAbsolutePath();
		if (scriptlibClassPath.startsWith(EngineConstants.PROPERTYSEPARATOR))
			scriptlibClassPath = scriptlibClassPath.substring(EngineConstants.PROPERTYSEPARATOR.length());
		config.setProperty(EngineConstants.WEBAPP_CLASSPATH_KEY, scriptlibClassPath);

		try {
			Platform.startup(config);
			logger.debug("Birt Platform started");
		} catch (BirtException e) {
			logger.error("Error during Birt Platform start-up", e);
		}

		IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
		birtEngine = factory.createReportEngine(config);
		logger.debug("Report engine created");

	}
	return birtEngine;
}
 
Example 20
Source File: KeenLogging.java    From KeenClient-Java with MIT License 2 votes vote down vote up
/**
 * Whether or not logging is enabled.
 *
 * @return a boolean saying whether or not logging is enabled
*/
public static boolean isLoggingEnabled() {
    return LOGGER.getLevel() == Level.FINER;
}