List of usage examples for java.util.logging LogManager getLogManager
public static LogManager getLogManager()
From source file:org.azyva.dragom.test.integration.IntegrationTestSuite.java
/** * Resets the test workspace.// www.j a va 2 s. co m */ public static void resetTestWorkspace() { InputStream inputStreamLoggingProperties; Path pathLoggingProperties; String loggingProperties; System.out.println("Resetting test workspace directory " + IntegrationTestSuite.pathTestWorkspace + '.'); try { LogManager.getLogManager().reset(); if (IntegrationTestSuite.pathTestWorkspace.toFile().exists()) { Path pathModel; InputStream inputStream; pathModel = IntegrationTestSuite.pathTestWorkspace.resolve("simple-model.xml"); inputStream = IntegrationTestSuite.class.getResourceAsStream("/simple-model.xml"); Files.copy(inputStream, pathModel, StandardCopyOption.REPLACE_EXISTING); inputStream.close(); System.setProperty("org.azyva.dragom.init-property.URL_MODEL", pathModel.toUri().toString()); try { ExecContextManagerTool.main(new String[] { "--workspace=" + IntegrationTestSuite.pathTestWorkspace.resolve("workspace"), "release" }); } catch (ExitException ee) { if (ee.status != 0) { throw ee; } } FileUtils.deleteDirectory(IntegrationTestSuite.pathTestWorkspace.toFile()); System.getProperties().remove("org.azyva.dragom.init-property.URL_MODEL"); } IntegrationTestSuite.pathTestWorkspace.toFile().mkdirs(); inputStreamLoggingProperties = IntegrationTestSuite.class.getResourceAsStream("/logging.properties"); pathLoggingProperties = IntegrationTestSuite.pathTestWorkspace.resolve("logging.properties"); Files.copy(inputStreamLoggingProperties, pathLoggingProperties, StandardCopyOption.REPLACE_EXISTING); inputStreamLoggingProperties.close(); loggingProperties = FileUtils.readFileToString(pathLoggingProperties.toFile()); loggingProperties = loggingProperties.replace("%test-workspace%", IntegrationTestSuite.pathTestWorkspace.toString()); FileUtils.write(pathLoggingProperties.toFile(), loggingProperties); inputStreamLoggingProperties = new FileInputStream(pathLoggingProperties.toFile()); LogManager.getLogManager().readConfiguration(inputStreamLoggingProperties); inputStreamLoggingProperties.close(); } catch (IOException ioe) { throw new RuntimeException(ioe); } }
From source file:com.afunms.common.util.logging.LogFactory.java
/** * {@link LogFactory} //from ww w .j a va2 s . c o m * <code>release()</code> * * @param classLoader <code>LogFactory</code> {@link ClassLoader} */ public static void release(@SuppressWarnings("unused") ClassLoader classLoader) { // JULI's log manager looks at the current classLoader LogManager.getLogManager().reset(); }
From source file:de.crowdcode.kissmda.maven.plugin.KissMdaMojo.java
private void setLoggingLevel() { Logger log = LogManager.getLogManager().getLogger(""); if (loggingLevel == null || loggingLevel.equals("")) { log.setLevel(Level.INFO); } else {/*w ww . j av a 2 s. c om*/ log.setLevel(loggingLevelMapper.getLevel(loggingLevel)); } for (Handler handler : log.getHandlers()) { if (loggingLevel == null || loggingLevel.equals("")) { handler.setLevel(Level.INFO); } else { handler.setLevel(loggingLevelMapper.getLevel(loggingLevel)); } } }
From source file:com.l2jfree.L2Config.java
/** Flushes all pending log entries. */ // FIXME MMOLogger.flush() public static void flush() { // those are redirected to loggers, so flush them first System.out.flush();/*from w w w . j av a 2 s . c o m*/ System.err.flush(); // then flush the loggers themselves final LogManager logManager = LogManager.getLogManager(); for (String loggerName : Collections.list(logManager.getLoggerNames())) { if (loggerName == null) continue; final Logger logger = logManager.getLogger(loggerName); if (logger == null) continue; for (Handler handler : logger.getHandlers()) if (handler != null) handler.flush(); } // and finally the real console streams L2Config.out.flush(); L2Config.err.flush(); }
From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java
@GET @RequireAdmin/*from ww w. j a v a 2 s .c o m*/ @APIDescription("Gets Loggers in the system") @Produces({ MediaType.APPLICATION_JSON }) @DataType(LoggerView.class) @Path("/loggers") public List<LoggerView> getLoggers() { List<LoggerView> loggers = new ArrayList<>(); List<String> allLoggers = LogManager.getLoggingMXBean().getLoggerNames(); Collections.sort(allLoggers); for (String name : allLoggers) { LoggerView loggerView = new LoggerView(); loggerView.setName(name); Level levelLocal = LogManager.getLogManager().getLogger(name).getLevel(); String levelName = ""; if (levelLocal != null) { levelName = levelLocal.getName(); } loggerView.setLevel(levelName); Logger localLogger = LogManager.getLogManager().getLogger(name); for (Handler handlerLocal : localLogger.getHandlers()) { loggerView.getHandlers() .add(handlerLocal.getClass().getName() + " = " + handlerLocal.getLevel().getName()); } loggers.add(loggerView); } return loggers; }
From source file:org.apache.juli.logging.LogFactory.java
/** * Release any internal references to previously created {@link LogFactory} * instances that have been associated with the specified class loader * (if any), after calling the instance method <code>release()</code> on * each of them./*from w ww. j a v a 2s.com*/ * * @param classLoader ClassLoader for which to release the LogFactory */ public static void release(ClassLoader classLoader) { // JULI's log manager looks at the current classLoader so there is no // need to use the passed in classLoader, the default implementation // does not so calling reset in that case will break things if (!LogManager.getLogManager().getClass().getName().equals("java.util.logging.LogManager")) { LogManager.getLogManager().reset(); } }
From source file:org.archive.crawler.Heritrix.java
public void instanceMain(String[] args) throws Exception { System.out.println(System.getProperty("java.vendor") + ' ' + System.getProperty("java.runtime.name") + ' ' + System.getProperty("java.runtime.version")); // ensure using java 1.6+ before hitting a later cryptic error String version = System.getProperty("java.version"); float floatVersion = Float.valueOf(version.substring(0, version.indexOf('.', 2))); if (floatVersion < 1.6) { System.err.println("Heritrix (as of version 3) requires Java 1.6 or higher."); System.err.println("You attempted to launch with: " + version); System.err.println("Please try again with a later Java."); System.exit(1);//from www. j a v a 2s . co m } // Set some system properties early. // Can't use class names here without loading them. String ignoredSchemes = "org.archive.net.UURIFactory.ignored-schemes"; if (System.getProperty(ignoredSchemes) == null) { System.setProperty(ignoredSchemes, "mailto, clsid, res, file, rtsp, about"); } String maxFormSize = "org.mortbay.jetty.Request.maxFormContentSize"; if (System.getProperty(maxFormSize) == null) { System.setProperty(maxFormSize, "52428800"); } BufferedOutputStream startupOutStream = new BufferedOutputStream( new FileOutputStream(new File(getHeritrixHome(), STARTLOG)), 16384); PrintStream startupOut = new PrintStream(new TeeOutputStream(System.out, startupOutStream)); CommandLine cl = getCommandLine(startupOut, args); if (cl == null) return; if (cl.hasOption('h')) { usage(startupOut, args); return; } // DEFAULTS until changed by cmd-line options int port = 8443; Set<String> bindHosts = new HashSet<String>(); String authLogin = "admin"; String authPassword = null; String keystorePath; String keystorePassword; String keyPassword; File properties = getDefaultPropertiesFile(); String aOption = cl.getOptionValue('a'); if (cl.hasOption('a')) { String usernameColonPassword = aOption; try { if (aOption.startsWith("@")) { usernameColonPassword = FileUtils.readFileToString(new File(aOption.substring(1))).trim(); } int colonIndex = usernameColonPassword.indexOf(':'); if (colonIndex > -1) { authLogin = usernameColonPassword.substring(0, colonIndex); authPassword = usernameColonPassword.substring(colonIndex + 1); } else { authPassword = usernameColonPassword; } } catch (IOException e) { // only if @filename read had problems System.err.println("Unable to read [username:]password from " + aOption); } } if (authPassword == null) { System.err.println("You must specify a valid [username:]password for the web interface using -a."); System.exit(1); authPassword = ""; // suppresses uninitialized warning } File jobsDir = null; if (cl.hasOption('j')) { jobsDir = new File(cl.getOptionValue('j')); } else { jobsDir = new File("./jobs"); } if (cl.hasOption('l')) { properties = new File(cl.getOptionValue('l')); } if (cl.hasOption('b')) { String hosts = cl.getOptionValue('b'); List<String> list; if ("/".equals(hosts)) { // '/' means all, signified by empty-list list = new ArrayList<String>(); } else { list = Arrays.asList(hosts.split(",")); } bindHosts.addAll(list); } else { // default: only localhost bindHosts.add("localhost"); } if (cl.hasOption('p')) { port = Integer.parseInt(cl.getOptionValue('p')); } // SSL options (possibly none, in which case adhoc keystore // is created or reused if (cl.hasOption('s')) { String[] sslParams = cl.getOptionValue('s').split(","); keystorePath = sslParams[0]; keystorePassword = sslParams[1]; keyPassword = sslParams[2]; } else { // use ad hoc keystore, creating if necessary keystorePath = ADHOC_KEYSTORE; keystorePassword = ADHOC_PASSWORD; keyPassword = ADHOC_PASSWORD; useAdhocKeystore(startupOut); } if (properties.exists()) { FileInputStream finp = new FileInputStream(properties); LogManager.getLogManager().readConfiguration(finp); finp.close(); } // Set timezone here. Would be problematic doing it if we're running // inside in a container. TimeZone.setDefault(TimeZone.getTimeZone("GMT")); setupGlobalProperties(port); // Start Heritrix. try { engine = new Engine(jobsDir); component = new Component(); if (bindHosts.isEmpty()) { // listen all addresses setupServer(port, null, keystorePath, keystorePassword, keyPassword); } else { // bind only to declared addresses, or just 'localhost' for (String address : bindHosts) { setupServer(port, address, keystorePath, keystorePassword, keyPassword); } } component.getClients().add(Protocol.FILE); component.getClients().add(Protocol.CLAP); Guard guard = new RateLimitGuard(null, ChallengeScheme.HTTP_DIGEST, "Authentication Required"); guard.getSecrets().put(authLogin, authPassword.toCharArray()); component.getDefaultHost().attach(guard); guard.setNext(new EngineApplication(engine)); component.start(); startupOut.println("engine listening at port " + port); startupOut.println( "operator login set per " + ((aOption.startsWith("@")) ? "file " + aOption : "command-line")); if (authPassword.length() < 8 || authPassword.matches("[a-zA-Z]{0,10}") || authPassword.matches("\\d{0,10}")) { startupOut.println("NOTE: We recommend a longer, stronger password, especially if your web \n" + "interface will be internet-accessible."); } if (cl.hasOption('r')) { engine.requestLaunch(cl.getOptionValue('r')); } } catch (Exception e) { // Show any exceptions in STARTLOG. e.printStackTrace(startupOut); if (component != null) { component.stop(); } throw e; } finally { startupOut.flush(); // stop writing to side startup file startupOutStream.close(); System.out.println("Heritrix version: " + ArchiveUtils.VERSION); } }
From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java
@PUT @RequireAdmin//from ww w . java2 s . c o m @APIDescription("Sets logger level") @Produces({ MediaType.APPLICATION_JSON }) @Consumes({ MediaType.WILDCARD }) @DataType(LoggerView.class) @Path("/logger/{loggername}/level") public Response updateApplicationProperty(@PathParam("loggername") @RequiredParam String loggername, String level) { Response response = Response.status(Response.Status.NOT_FOUND).build(); Logger logger = LogManager.getLogManager().getLogger(loggername); if (logger != null) { List<String> levels = loadLevels(); boolean saved = false; if (StringUtils.isBlank(level)) { logger.setLevel(null); saved = true; } else { if (levels.contains(level)) { logger.setLevel(Level.parse(level)); saved = true; } else { RestErrorModel restErrorModel = new RestErrorModel(); restErrorModel.getErrors().put("level", "Log level is not valid. Check level value passed in."); response = Response.ok(restErrorModel).build(); } } if (saved) { LoggerView loggerView = new LoggerView(); loggerView.setName(loggername); loggerView.setLevel(level); for (Handler handlerLocal : logger.getHandlers()) { loggerView.getHandlers() .add(handlerLocal.getClass().getName() + " = " + handlerLocal.getLevel().getName()); } response = Response.ok(loggerView).build(); } } return response; }
From source file:de.fosd.jdime.Main.java
/** * Ensures that logging is configured. If the system property is set to an existing file then nothing is done as * that config was already read at JVM startup. If not, a file named {@value LOGGING_CONFIG_FILE} in * the working directory is used if it exists. If it does not, the default configuration file is read from the * classpath.// w w w. j av a2 s .c o m */ private static void readLoggingConfig() { { String logConfigProperty = System.getProperty(LOGGING_CONFIG_FILE_PROPERTY); if (logConfigProperty != null && new File(logConfigProperty).exists()) { // The config file was already read at JVM startup. return; } } try { File configFile = new File(LOGGING_CONFIG_FILE); InputStream is; if (configFile.exists()) { is = FileUtils.openInputStream(configFile); } else { System.err.println("Logging configuration file " + configFile + " does not exist. " + "Falling back to defaults."); is = Main.class.getResourceAsStream(DEFAULT_LOGGING_CONFIG_FILE); if (is == null) { System.err.println("Could not find the default logging configuration."); return; } } try { LogManager.getLogManager().readConfiguration(is); } finally { try { is.close(); } catch (IOException ignored) { } } } catch (IOException e) { System.err.println("Failed to configure logging."); e.printStackTrace(); } }
From source file:org.jenkinsci.maven.plugins.hpi.RunMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { getProject().setArtifacts(resolveDependencies(dependencyResolution)); File basedir = getProject().getBasedir(); if (webApp == null || webApp.getContextPath() == null) { if (contextPath != null) { getLog().warn(/*from ww w . ja v a 2 s. c om*/ "Please use `webApp/contextPath` configuration parameter in place of the deprecated `contextPath` parameter"); if (webApp == null) { try { webApp = new JettyWebAppContext(); } catch (Exception e) { throw new MojoExecutionException("Failed to initialize webApp configuration", e); } } webApp.setContextPath(contextPath); } } // compute jenkinsHome if (jenkinsHome == null) { if (hudsonHome != null) { getLog().warn( "Please use the `jenkinsHome` configuration parameter in place of the deprecated `hudsonHome` parameter"); jenkinsHome = hudsonHome; } String h = System.getenv("JENKINS_HOME"); if (h == null) { h = System.getenv("HUDSON_HOME"); } if (h != null) jenkinsHome = new File(h); else jenkinsHome = new File(basedir, "work"); } // auto-enable stapler trace, unless otherwise configured already. setSystemPropertyIfEmpty("stapler.trace", "true"); // allow Jetty to accept a bigger form so that it can handle update center JSON post setSystemPropertyIfEmpty("org.eclipse.jetty.Request.maxFormContentSize", "-1"); // general-purpose system property so that we can tell from Jenkins if we are running in the hpi:run mode. setSystemPropertyIfEmpty("hudson.hpi.run", "true"); // this adds 3 secs to the shutdown time. Skip it. setSystemPropertyIfEmpty("hudson.DNSMultiCast.disabled", "true"); // expose the current top-directory of the plugin setSystemPropertyIfEmpty("jenkins.moduleRoot", basedir.getAbsolutePath()); if (systemProperties != null && !systemProperties.isEmpty()) { for (Map.Entry<String, String> entry : systemProperties.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { System.setProperty(entry.getKey(), entry.getValue()); } } } // look for jenkins.war Artifacts jenkinsArtifacts = Artifacts.of(getProject()) .groupIdIs("org.jenkins-ci.main", "org.jvnet.hudson.main").artifactIdIsNot("remoting"); // remoting moved to its own release cycle webAppFile = getJenkinsWarArtifact().getFile(); // make sure all the relevant Jenkins artifacts have the same version for (Artifact a : jenkinsArtifacts) { Artifact ba = jenkinsArtifacts.get(0); if (!a.getVersion().equals(ba.getVersion())) throw new MojoExecutionException("Version of " + a.getId() + " is inconsistent with " + ba.getId()); } // set JENKINS_HOME setSystemPropertyIfEmpty("JENKINS_HOME", jenkinsHome.getAbsolutePath()); File pluginsDir = new File(jenkinsHome, "plugins"); pluginsDir.mkdirs(); // enable view auto refreshing via stapler setSystemPropertyIfEmpty("stapler.jelly.noCache", "true"); List<Resource> res = getProject().getBuild().getResources(); if (!res.isEmpty()) { // pick up the first one and use it Resource r = res.get(0); setSystemPropertyIfEmpty("stapler.resourcePath", r.getDirectory()); } generateHpl(); // copy other dependency Jenkins plugins try { for (MavenArtifact a : getProjectArtifacts()) { if (!a.isPlugin()) continue; // find corresponding .hpi file Artifact hpi = artifactFactory.createArtifact(a.getGroupId(), a.getArtifactId(), a.getVersion(), null, "hpi"); artifactResolver.resolve(hpi, getProject().getRemoteArtifactRepositories(), localRepository); // check recursive dependency. this is a rare case that happens when we split out some things from the core // into a plugin if (hasSameGavAsProject(hpi)) continue; if (hpi.getFile().isDirectory()) throw new UnsupportedOperationException( hpi.getFile() + " is a directory and not packaged yet. this isn't supported"); File upstreamHpl = pluginWorkspaceMap.read(hpi.getId()); if (upstreamHpl != null) { copyHpl(upstreamHpl, pluginsDir, a.getActualArtifactId()); } else { copyPlugin(hpi.getFile(), pluginsDir, a.getActualArtifactId()); } } } catch (IOException e) { throw new MojoExecutionException("Unable to copy dependency plugin", e); } catch (ArtifactNotFoundException e) { throw new MojoExecutionException("Unable to copy dependency plugin", e); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Unable to copy dependency plugin", e); } if (loggers != null) { for (Handler h : LogManager.getLogManager().getLogger("").getHandlers()) { if (h instanceof ConsoleHandler) { h.setLevel(Level.ALL); } } loggerReferences = new LinkedList<Logger>(); for (Map.Entry<String, String> logger : loggers.entrySet()) { Logger l = Logger.getLogger(logger.getKey()); loggerReferences.add(l); l.setLevel(Level.parse(logger.getValue())); } } super.execute(); }