List of usage examples for java.util.logging Logger addHandler
public void addHandler(Handler handler) throws SecurityException
From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java
@Test public void buildShellScriptAcrossRestart() throws Exception { Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows()); story.addStep(new Statement() { @SuppressWarnings("SleepWhileInLoop") @Override// w ww . j ava 2s . c o m public void evaluate() throws Throwable { Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName()); LOGGER.setLevel(Level.FINE); Handler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398. // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off). DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1", Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); story.j.jenkins.addNode(s); startJnlpProc(); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo"); File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); new FileOutputStream(f1).close(); p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + " sh 'touch \"" + f2 + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2 + "\"'\n" + " echo 'OK, done'\n" + "}", true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); while (!f2.isFile()) { Thread.sleep(100); } assertTrue(b.isBuilding()); killJnlpProc(); } }); story.addStep(new Statement() { @Override public void evaluate() throws Throwable { WorkflowJob p = (WorkflowJob) story.j.jenkins.getItem("demo"); WorkflowRun b = p.getLastBuild(); assertTrue(b.isBuilding()); // TODO occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight) startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before. File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); assertTrue(f2.isFile()); assertTrue(f1.delete()); while (f2.isFile()) { Thread.sleep(100); } story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b)); story.j.assertLogContains("finished waiting", b); story.j.assertLogContains("OK, done", b); killJnlpProc(); } }); }
From source file:org.archive.crawler.reporting.CrawlerLoggerModule.java
protected void rotateLogFiles(String generationSuffix, boolean mergeOld) throws IOException { for (Logger l : fileHandlers.keySet()) { GenerationFileHandler gfh = (GenerationFileHandler) fileHandlers.get(l); GenerationFileHandler newGfh = gfh.rotate(generationSuffix, "", mergeOld); if (gfh.shouldManifest()) { addToManifest((String) newGfh.getFilenameSeries().get(1), MANIFEST_LOG_FILE, newGfh.shouldManifest()); }//from ww w . j a v a 2 s. co m l.removeHandler(gfh); l.addHandler(newGfh); fileHandlers.put(l, newGfh); } }
From source file:hudson.plugins.active_directory.docker.TheFlintstonesTest.java
private List<String> captureLogMessages(int size) { final List<String> logMessages = new ArrayList<>(size); Logger logger = Logger.getLogger(""); logger.setLevel(Level.ALL);// ww w. ja va 2 s .c o m RingBufferLogHandler ringHandler = new RingBufferLogHandler(size) { final Formatter f = new SimpleFormatter(); // placeholder instance for what should have been a static method perhaps @Override public synchronized void publish(LogRecord record) { super.publish(record); String message = f.formatMessage(record); Throwable x = record.getThrown(); logMessages.add(message == null && x != null ? x.toString() : message); } }; logger.addHandler(ringHandler); return logMessages; }
From source file:com.ebixio.virtmus.stats.StatsLogger.java
/** Called when the log handler changes (when the logs are rotated). */ private synchronized boolean changeHandler(Handler newLogHandler) { if (newLogHandler == null) return false; Logger uiLogger = Logger.getLogger("org.netbeans.ui"); if (logHandler != null) { statsLog.removeHandler(logHandler); uiLogger.removeHandler(logHandler); logHandler.close();//from w w w . ja va 2 s.c o m } statsLog.addHandler(newLogHandler); uiLogger.addHandler(newLogHandler); logHandler = newLogHandler; return true; }
From source file:org.jenkinsci.plugins.workflow.WorkflowTest.java
@RandomlyFails("never printed 'finished waiting'") @Test/*www . j av a 2s .c o m*/ public void buildShellScriptAcrossDisconnect() throws Exception { story.addStep(new Statement() { @SuppressWarnings("SleepWhileInLoop") @Override public void evaluate() throws Throwable { Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName()); LOGGER.setLevel(Level.FINE); Handler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1", Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); story.j.jenkins.addNode(s); startJnlpProc(); p = story.j.jenkins.createProject(WorkflowJob.class, "demo"); File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); new FileOutputStream(f1).close(); p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + " sh 'touch \"" + f2 + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2 + "\"'\n" + " echo 'OK, done'\n" + "}")); startBuilding(); while (!f2.isFile()) { Thread.sleep(100); } assertTrue(b.isBuilding()); Computer c = s.toComputer(); assertNotNull(c); killJnlpProc(); while (c.isOnline()) { Thread.sleep(100); } startJnlpProc(); while (c.isOffline()) { Thread.sleep(100); } assertTrue(f2.isFile()); assertTrue(f1.delete()); while (f2.isFile()) { Thread.sleep(100); } story.j.assertBuildStatusSuccess(JenkinsRuleExt.waitForCompletion(b)); story.j.assertLogContains("finished waiting", b); story.j.assertLogContains("OK, done", b); killJnlpProc(); } }); }
From source file:org.jenkinsci.plugins.workflow.WorkflowTest.java
@RandomlyFails("TODO isBuilding assertion after restart occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight)") @Test//from w ww. ja va2 s . c om public void buildShellScriptAcrossRestart() throws Exception { story.addStep(new Statement() { @SuppressWarnings("SleepWhileInLoop") @Override public void evaluate() throws Throwable { Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName()); LOGGER.setLevel(Level.FINE); Handler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398. // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off). DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1", Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList()); story.j.jenkins.addNode(s); startJnlpProc(); p = story.j.jenkins.createProject(WorkflowJob.class, "demo"); File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); new FileOutputStream(f1).close(); p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + " sh 'touch \"" + f2 + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2 + "\"'\n" + " echo 'OK, done'\n" + "}")); startBuilding(); while (!f2.isFile()) { Thread.sleep(100); } assertTrue(b.isBuilding()); killJnlpProc(); } }); story.addStep(new Statement() { @Override public void evaluate() throws Throwable { rebuildContext(story.j); assertTrue(b.isBuilding()); startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before. File f1 = new File(story.j.jenkins.getRootDir(), "f1"); File f2 = new File(story.j.jenkins.getRootDir(), "f2"); assertTrue(f2.isFile()); assertTrue(f1.delete()); while (f2.isFile()) { Thread.sleep(100); } story.j.assertBuildStatusSuccess(JenkinsRuleExt.waitForCompletion(b)); story.j.assertLogContains("finished waiting", b); story.j.assertLogContains("OK, done", b); killJnlpProc(); } }); }
From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java
/** * Register {@link Handler log handler} to the list of root loggers. *//* w ww .ja v a 2 s . c o m*/ private void registerLogHandler() { final String recordLogLevel = getProperty(TestProperties.RECORD_LOG_LEVEL); final int recordLogLevelInt = Integer.valueOf(recordLogLevel); final Level level = Level.parse(recordLogLevel); logLevelMap.clear(); for (final Logger root : getRootLoggers()) { logLevelMap.put(root, root.getLevel()); if (root.getLevel().intValue() > recordLogLevelInt) { root.setLevel(level); } root.addHandler(getLogHandler()); } }
From source file:org.rzo.yajsw.app.WrapperManagerImpl.java
public void init(String[] args, ClassLoader wrapperClassLoader) { /*//from w ww. j a v a2 s. c o m * System.out.println(Scheduler.class.getClassLoader()); * System.out.println(Configuration.class.getClassLoader()); * System.out.flush(); try { Thread.sleep(10000); } catch * (InterruptedException e1) { // TODO Auto-generated catch block * e1.printStackTrace(); } */ ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(wrapperClassLoader); instance = this; String outFile = System.getProperty("wrapper.teeName"); String outPath = System.getProperty("wrapper.tmpPath"); String vStr = System.getProperty("wrapper.console.visible"); boolean visible = vStr != null && vStr.equals("true"); if (outFile != null) { teeSystemStreams(outFile, outPath, visible); } logJavaInfo(args); String preScript = System.getProperty("wrapper.app.pre.script"); if (preScript != null & !"".equals(preScript)) { Logger logger = new MyLogger(); logger.addHandler(new ConsoleHandler()); Script script = ScriptFactory.createScript(preScript, "", null, new String[0], null); if (script != null) script.execute(); } YajswConfigurationImpl config = new YajswConfigurationImpl(); //config.setDebug(false); config.init(); try { _overrideStdErr = config.getBoolean("wrapper.java.dump.override", false); } catch (Exception ex) { System.out.println("Error getting wrapper.java.dump.override " + ex.getMessage()); } String mainClassName = config.getString("wrapper.java.app.mainclass"); String jarName = config.getString("wrapper.java.app.jar"); String groovyScript = config.getString("wrapper.groovy"); if (mainClassName == null && jarName == null && groovyScript == null) mainClassName = config.getString("wrapper.app.parameter.1"); if (jarName == null && mainClassName == null && groovyScript == null) { System.out.println("missing main class name or jar file or groovy file. please check configuration"); return; } if (jarName != null) { mainMethod = loadJar(jarName); } else if (mainClassName != null) try { Class cls = ClassLoader.getSystemClassLoader().loadClass(mainClassName);// Class.forName(mainClassName, // currentContext); mainMethod = cls.getDeclaredMethod("main", new Class[] { String[].class }); } catch (Exception e) { System.out.println("error finding main method in class: " + mainClassName + " : " + e.getMessage()); // log.throwing(WrapperMain.class.getName(), "main", e); e.printStackTrace(); return; } else _groovyScript = groovyScript; String stopConfig = config.getString("wrapper.stop.conf"); if (stopConfig != null) { File f = new File(stopConfig); _externalStop = true; } System.out.println("external stop " + _externalStop); exitOnMainTerminate = config.getInt("wrapper.exit_on_main_terminate", DEFAULT_EXIT_ON_MAIN_TERMINATE); exitOnException = config.getInt("wrapper.exit_on_main_exception", DEFAULT_EXIT_ON_MAIN_EXCEPTION); mainMethodArgs = getAppParam((Configuration) config); setConfiguration((Configuration) config); if (_config.getBoolean("wrapper.java.jmx", false)) registerMBean(config); String control = _config.getString("wrapper.control", DEFAULT_CONTROL); if ("TIGHT".equals(control) || "APPLICATION".equals(control)) _haltAppOnWrapper = true; Thread.currentThread().setContextClassLoader(currentClassLoader); setKey(_config.getString("wrapper.key")); // setDebug(true); setPort(_config.getInt("wrapper.port")); setPingInterval(_config.getInt("wrapper.ping.interval", Constants.DEFAULT_PING_INTERVAL)); _startupTimeout = _config.getInt("wrapper.startup.timeout", DEFAULT_STARTUP_TIMEOUT) * 1000; _debug = _config.getBoolean("wrapper.debug", false); }
From source file:edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean.java
/** * Run a harvest for an individual harvesting Dataverse * @param dataverseRequest/*from w ww . j a va2 s . c o m*/ * @param harvestingClientId * @throws IOException */ public void doHarvest(DataverseRequest dataverseRequest, Long harvestingClientId) throws IOException { HarvestingClient harvestingClientConfig = harvestingClientService.find(harvestingClientId); if (harvestingClientConfig == null) { throw new IOException("No such harvesting client: id=" + harvestingClientId); } Dataverse harvestingDataverse = harvestingClientConfig.getDataverse(); MutableBoolean harvestErrorOccurred = new MutableBoolean(false); String logTimestamp = logFormatter.format(new Date()); Logger hdLogger = Logger.getLogger("edu.harvard.iq.dataverse.harvest.client.HarvesterServiceBean." + harvestingDataverse.getAlias() + logTimestamp); String logFileName = "../logs" + File.separator + "harvest_" + harvestingClientConfig.getName() + "_" + logTimestamp + ".log"; FileHandler fileHandler = new FileHandler(logFileName); hdLogger.setUseParentHandlers(false); hdLogger.addHandler(fileHandler); PrintWriter importCleanupLog = new PrintWriter(new FileWriter( "../logs/harvest_cleanup_" + harvestingClientConfig.getName() + "_" + logTimestamp + ".txt")); List<Long> harvestedDatasetIds = null; List<Long> harvestedDatasetIdsThisBatch = new ArrayList<Long>(); List<String> failedIdentifiers = new ArrayList<String>(); List<String> deletedIdentifiers = new ArrayList<String>(); Date harvestStartTime = new Date(); try { boolean harvestingNow = harvestingClientConfig.isHarvestingNow(); if (harvestingNow) { harvestErrorOccurred.setValue(true); hdLogger.log(Level.SEVERE, "Cannot begin harvesting, Dataverse " + harvestingDataverse.getName() + " is currently being harvested."); } else { harvestingClientService.resetHarvestInProgress(harvestingClientId); harvestingClientService.setHarvestInProgress(harvestingClientId, harvestStartTime); if (harvestingClientConfig.isOai()) { harvestedDatasetIds = harvestOAI(dataverseRequest, harvestingClientConfig, hdLogger, importCleanupLog, harvestErrorOccurred, failedIdentifiers, deletedIdentifiers, harvestedDatasetIdsThisBatch); } else { throw new IOException("Unsupported harvest type"); } harvestingClientService.setHarvestSuccess(harvestingClientId, new Date(), harvestedDatasetIds.size(), failedIdentifiers.size(), deletedIdentifiers.size()); hdLogger.log(Level.INFO, "COMPLETED HARVEST, server=" + harvestingClientConfig.getArchiveUrl() + ", metadataPrefix=" + harvestingClientConfig.getMetadataPrefix()); hdLogger.log(Level.INFO, "Datasets created/updated: " + harvestedDatasetIds.size() + ", datasets deleted: " + deletedIdentifiers.size() + ", datasets failed: " + failedIdentifiers.size()); // now index all the datasets we have harvested - created, modified or deleted: /* (TODO: may not be needed at all. In Dataverse4, we may be able to get away with the normal reindexing after every import. See the rest of the comments about batch indexing throughout this service bean) if (this.processedSizeThisBatch > 0) { hdLogger.log(Level.INFO, "POST HARVEST, reindexing the remaining studies."); if (this.harvestedDatasetIdsThisBatch != null) { hdLogger.log(Level.INFO, this.harvestedDatasetIdsThisBatch.size()+" studies in the batch"); } hdLogger.log(Level.INFO, this.processedSizeThisBatch + " bytes of content"); indexService.updateIndexList(this.harvestedDatasetIdsThisBatch); hdLogger.log(Level.INFO, "POST HARVEST, calls to index finished."); } else { hdLogger.log(Level.INFO, "(All harvested content already reindexed)"); } */ } //mailService.sendHarvestNotification(...getSystemEmail(), harvestingDataverse.getName(), logFileName, logTimestamp, harvestErrorOccurred.booleanValue(), harvestedDatasetIds.size(), failedIdentifiers); } catch (Throwable e) { harvestErrorOccurred.setValue(true); String message = "Exception processing harvest, server= " + harvestingClientConfig.getHarvestingUrl() + ",format=" + harvestingClientConfig.getMetadataPrefix() + " " + e.getClass().getName() + " " + e.getMessage(); hdLogger.log(Level.SEVERE, message); logException(e, hdLogger); hdLogger.log(Level.INFO, "HARVEST NOT COMPLETED DUE TO UNEXPECTED ERROR."); // TODO: // even though this harvesting run failed, we may have had successfully // processed some number of datasets, by the time the exception was thrown. // We should record that number too. And the number of the datasets that // had failed, that we may have counted. -- L.A. 4.4 harvestingClientService.setHarvestFailure(harvestingClientId, new Date()); } finally { harvestingClientService.resetHarvestInProgress(harvestingClientId); fileHandler.close(); hdLogger.removeHandler(fileHandler); importCleanupLog.close(); } }
From source file:org.ebayopensource.turmeric.plugins.maven.AbstractTurmericMojo.java
/** * Wraps the mojo execute with some behavioral lifecycle. *//* w w w . j av a 2 s . c o m*/ @Override public final void execute() throws MojoExecutionException, MojoFailureException { getLog().debug("[execute]"); getLog().info("Using turmeric-maven-plugin version " + getTurmericMavenPluginVersion()); if (executeSkip()) { getLog().warn("Skipping execution"); return; } if (verbose) { logDependencyDetails("Turmeric Maven Plugin", AbstractTurmericMojo.class, GROUPID_SELF, ARTIFACTID_SELF); logDependencyDetails("Codegen Tools", NonInteractiveCodeGen.class, "org.ebayopensource.turmeric.runtime", "soa-client"); getLog().info("Verbose Mode: enabling java.util.logging"); // Initialize java.util.logging (which is present in CodeGen classes) Logger root = Logger.getLogger(""); // Remove old delegates for (Handler handler : root.getHandlers()) { getLog().info("Removing existing logging handler: " + handler.getClass().getName()); root.removeHandler(handler); } // Add our delegate root.addHandler(new LogDelegateHandler(getLog())); } getLog().debug("[onValidateParameters]"); onValidateParameters(); // Test for need to generate getLog().debug("[needsGeneration]"); if (needsGeneration() == false) { getLog().warn("No need to generate. skipping turmeric plugin execution."); return; } try { getLog().debug("[onRunSetup]"); onRunSetup(); // Attach directories to project even if skipping servicegen. // This is to be a good maven and m2eclipse citizen. getLog().debug("[onAttachGeneratedDirectories]"); onAttachGeneratedDirectories(); getLog().debug("[onRun]"); onRun(); } finally { getLog().debug("[onRunTearDown]"); onRunTearDown(); } }