/** * Options are activated and become effective only after calling this method. */ public void start() { int errors = 0; if (this.layout == null) { addStatus(new ErrorStatus("No layout set for the RocketmqLogbackAppender named \"" + name + "\".", this)); errors++; } if (errors > 0 || !checkEntryConditions()) { return; } try { producer = ProducerInstance.getInstance(nameServerAddress, producerGroup); } catch (Exception e) { addError("Starting RocketmqLogbackAppender [" + this.getName() + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage()); } if (producer != null) { super.start(); } }
/** * Checks that the required parameters are set and if everything is in * order, activates this appender. */ @Override public void start() { boolean error = false; if (this.encoder == null) { error = true; addStatus( new ErrorStatus( "No encoder set for the appender named [" + name + "].", this ) ); } if (!error) { super.start(); } }
private void multiplicityWarning(String resourceName, ClassLoader classLoader) { Set urlSet = null; StatusManager sm = this.loggerContext.getStatusManager(); try { urlSet = Loader.getResourceOccurrenceCount(resourceName, classLoader); } catch (IOException var7) { sm.add(new ErrorStatus("Failed to get url list for resource [" + resourceName + "]", this.loggerContext, var7)); } if (urlSet != null && urlSet.size() > 1) { sm.add(new WarnStatus("Resource [" + resourceName + "] occurs multiple times on the classpath.", this.loggerContext)); Iterator i$ = urlSet.iterator(); while (i$.hasNext()) { URL url = (URL) i$.next(); sm.add(new WarnStatus("Resource [" + resourceName + "] occurs at [" + url.toString() + "]", this.loggerContext)); } } }
/** * Options are activated and become effective only after calling this method. */ public void start() { int errors = 0; if (this.layout == null) { addStatus(new ErrorStatus("No layout set for the RocketmqLogbackAppender named \"" + name + "\".", this)); errors++; } if (errors > 0 || !checkEntryConditions()) { return; } try { producer = ProducerInstance.getProducerInstance().getInstance(nameServerAddress, producerGroup); } catch (Exception e) { addError("Starting RocketmqLogbackAppender [" + this.getName() + "] nameServerAddress:" + nameServerAddress + " group:" + producerGroup + " " + e.getMessage()); } if (producer != null) { super.start(); } }
@Override public void start() { int errors = 0; if (level == null) { addStatus(new ErrorStatus("No level set for the appender named \"" + name + "\".", this)); errors++; } if (endpoint == null) { addStatus(new ErrorStatus("No endpoint set for the appender named \"" + name + "\".", this)); errors++; } if (layout == null) { addStatus(new ErrorStatus("No layout set for the appender named \"" + name + "\".", this)); errors++; } if (errors == 0) { super.start(); } }
public void start() { if(pattern == null || pattern.length() == 0) { addError("Empty or null pattern."); return; } try { Parser<E> p = new Parser<E>(pattern); if (getContext() != null) { p.setContext(getContext()); } Node t = p.parse(); this.head = p.compile(t, getEffectiveConverterMap()); if (postCompileProcessor != null) { postCompileProcessor.process(head); } ConverterUtil.setContextForConverters(getContext(), head); ConverterUtil.startConverters(this.head); super.start(); } catch (ScanException sce) { StatusManager sm = getContext().getStatusManager(); sm.add(new ErrorStatus("Failed to parse pattern \"" + getPattern() + "\".", this, sce)); } }
/** * Checks that requires parameters are set and if everything is in order, * activates this appender. */ public void start() { int errors = 0; if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this)); errors++; } if (this.outputStream == null) { addStatus(new ErrorStatus( "No output stream set for the appender named \"" + name + "\".", this)); errors++; } // only error free appenders should be activated if (errors == 0) { super.start(); } }
/** * Actual writing occurs here. * <p> * Most subclasses of <code>WriterAppender</code> will need to override this * method. * * @since 0.9.0 */ protected void subAppend(E event) { if (!isStarted()) { return; } try { // this step avoids LBCLASSIC-139 if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } // the synchronization prevents the OutputStream from being closed while we // are writing. It also prevents multiple threads from entering the same // converter. Converters assume that they are in a synchronized block. lock.lock(); try { writeOut(event); } finally { lock.unlock(); } } catch (IOException ioe) { // as soon as an exception occurs, move to non-started state // and add a single ErrorStatus to the SM. this.started = false; addStatus(new ErrorStatus("IO failure in appender", this, ioe)); } }
@Test public void many() { int margin = 300; int len = MAX_HEADER_COUNT + TAIL_SIZE + margin; for (int i = 0; i < len; i++) { bsm.add(new ErrorStatus("" + i, this)); } List<Status> statusList = bsm.getCopyOfStatusList(); assertNotNull(statusList); assertEquals(MAX_HEADER_COUNT + TAIL_SIZE, statusList.size()); List<Status> witness = new ArrayList<Status>(); for (int i = 0; i < MAX_HEADER_COUNT; i++) { witness.add(new ErrorStatus("" + i, this)); } for (int i = 0; i < TAIL_SIZE; i++) { witness.add(new ErrorStatus("" + (MAX_HEADER_COUNT + margin + i), this)); } assertEquals(witness, statusList); }
public void configureByResource(URL url) throws JoranException { if (url == null) { throw new IllegalArgumentException("URL argument cannot be null"); } final String urlString = url.toString(); if (urlString.endsWith("groovy")) { if (EnvUtil.isGroovyAvailable()) { // avoid directly referring to GafferConfigurator so as to avoid // loading groovy.lang.GroovyObject . See also http://jira.qos.ch/browse/LBCLASSIC-214 GafferUtil.runGafferConfiguratorOn(loggerContext, this, url); } else { StatusManager sm = loggerContext.getStatusManager(); sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", loggerContext)); } } else if (urlString.endsWith("xml")) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(url); } else { throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml"); } }
private void multiplicityWarning(String resourceName, ClassLoader classLoader) { Set<URL> urlSet = null; StatusManager sm = loggerContext.getStatusManager(); try { urlSet = Loader.getResourceOccurrenceCount(resourceName, classLoader); } catch (IOException e) { sm.add(new ErrorStatus("Failed to get url list for resource [" + resourceName + "]", loggerContext, e)); } if (urlSet != null && urlSet.size() > 1) { sm.add(new WarnStatus("Resource [" + resourceName + "] occurs multiple times on the classpath.", loggerContext)); for (URL url : urlSet) { sm.add(new WarnStatus("Resource [" + resourceName + "] occurs at [" + url.toString() + "]", loggerContext)); } } }
@Test public void zeroNesting() throws JoranException { configure(SIFT_FOLDER_PREFIX + "zeroNesting.xml"); logger.debug("hello"); logger.debug("hello"); logger.debug("hello"); logger.debug("hello"); logger.debug("hello"); SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); Appender<ILoggingEvent> appender = getAppenderTracker().find("zeroDefault"); assertNotNull(appender); NOPAppender<ILoggingEvent> nopa = (NOPAppender<ILoggingEvent>) appender; StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); statusChecker.assertContainsMatch(ErrorStatus.ERROR, "No nested appenders found"); }
@Override public synchronized void stop() { if (!isStarted()) { return; } try { this.encoder.close(); // no need to restore System.out (due to buffering, better not to do that) } catch (final IOException ex) { addStatus(new ErrorStatus("Failed to write footer for appender named \"" + this.name + "\".", this, ex)); } finally { super.stop(); } }
@Override protected synchronized void append(final E event) { if (!isStarted()) { return; } try { if (event instanceof DeferredProcessingAware) { ((DeferredProcessingAware) event).prepareForDeferredProcessing(); } this.encoder.doEncode(event); } catch (final IOException ex) { stop(); addStatus(new ErrorStatus("IO failure in appender named \"" + this.name + "\".", this, ex)); } }
/** * * @param eventObject */ private void subAppend(ILoggingEvent eventObject) { if (!isStarted()) { return; } try { // this step avoids LBCLASSIC-139 if (eventObject instanceof DeferredProcessingAware) { ((DeferredProcessingAware) eventObject).prepareForDeferredProcessing(); } this.encoder.doEncode(eventObject); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus("IO failure in appender", this, ioe)); } }
@Override public void start() { try { if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + name + "\".", this)); return; } close(); this.sqs = new AmazonSQSAsyncClient(getCredentials(), this.threadPool > 0 ? Executors.newFixedThreadPool(this.threadPool) : Executors.newCachedThreadPool()); this.sqs.setEndpoint(new URI(this.queueUrl).getHost()); this.encoder.init(new SqsOutputStreamAdapter()); super.start(); } catch (Exception e) { addError(this.getClass() + " start failure", e); } }
@Test public void testDontStartWithoutTopic() { unit.setTopic(null); unit.start(); assertFalse("isStarted", unit.isStarted()); assertThat(ctx.getStatusManager().getCopyOfStatusList(), hasItem(new ErrorStatus("No topic set for the appender named [\"kafkaAppenderBase\"].", null))); }
@Test public void testDontStartWithoutBoostrapServers() { unit.getProducerConfig().clear(); unit.start(); assertFalse("isStarted", unit.isStarted()); assertThat(ctx.getStatusManager().getCopyOfStatusList(), hasItem(new ErrorStatus("No \"bootstrap.servers\" set for the appender named [\"kafkaAppenderBase\"].", null))); }
@Test public void testDontStartWithoutEncoder() { unit.setEncoder(null); unit.start(); assertFalse("isStarted", unit.isStarted()); assertThat(ctx.getStatusManager().getCopyOfStatusList(), hasItem(new ErrorStatus("No encoder set for the appender named [\"kafkaAppenderBase\"].", null))); }
@Override public synchronized void start() { if (isStarted()) { return; } if (layout == null) { layout = new EchoLayout<>(); addStatus(new WarnStatus("No layout, default to " + layout, this)); } if (logGroupName == null) { logGroupName = getClass().getSimpleName(); addStatus(new WarnStatus("No logGroupName, default to " + logGroupName, this)); } if (logStreamName == null) { logStreamName = new SimpleDateFormat("yyyyMMdd'T'HHmmss").format(new Date()); addStatus(new WarnStatus("No logGroupName, default to " + logStreamName, this)); } try { if (awsLogs == null) { awsLogs = AWSLogsClientBuilder.defaultClient(); } createLogGroup(); createLogStream(); } catch (final AmazonClientException e) { awsLogs = null; addStatus(new ErrorStatus(e.getMessage(), this, e)); } // Start a new daemon time thread to periodically upload events // Because this is a deamon thread, it will not block shutdown new DaemonTimerThread().start(); // Add a shutdown hook to catch any final events at shutdown Runtime.getRuntime().addShutdownHook(new ShutdownHook()); layout.start(); super.start(); }
@Override public void start() { if (this.encoder == null) { addStatus(new ErrorStatus("No encoder set for the appender named \"" + this.name + "\".", this)); return; } super.start(); }
public void setMinInterval(String minInterval) { try { this.minInterval = Integer.parseInt(minInterval); } catch (NumberFormatException e) { addStatus(new ErrorStatus("Bad minInterval for the appender named \"" + name + "\". Leaving to defaultValue ", this)); } }
public void setConnectTimeout(String connectTimeout) { try { this.connectTimeout = Integer.parseInt(connectTimeout); } catch (NumberFormatException e) { addStatus(new ErrorStatus("Bad connectTimeout for the appender named \"" + name + "\". Leaving to defaultValue ", this)); } }
public void setConnectionRequestTimeout(String connectionRequestTimeout) { try { this.connectionRequestTimeout = Integer.parseInt(connectionRequestTimeout); } catch (NumberFormatException e) { addStatus(new ErrorStatus("Bad connectionRequestTimeout for the appender named \"" + name + "\". Leaving to defaultValue ", this)); } }
public void setSocketTimeout(String socketTimeout) { try { this.socketTimeout = Integer.parseInt(socketTimeout); } catch (NumberFormatException e) { addStatus(new ErrorStatus("Bad socketTimeout for the appender named \"" + name + "\". Leaving to defaultValue ", this)); } }
@Override protected void append(E eventObject) { try { synchronized (eventListLock) { eventList.add(eventObject); } } catch (Exception e) { addStatus(new ErrorStatus( getName() + " failed to append event: " + e.getLocalizedMessage(), this, e) ); } }
/** * Close the underlying {@link OutputStream}. */ protected void closeOutputStream() { if (this.outputStream != null) { try { // before closing we have to output out layout's footer encoderClose(); this.outputStream.close(); this.outputStream = null; } catch (IOException e) { addStatus(new ErrorStatus( "Could not close output stream for OutputStreamAppender.", this, e)); } } }
void encoderInit() { if (encoder != null && this.outputStream != null) { try { encoder.init(outputStream); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus( "Failed to initialize encoder for appender named [" + name + "].", this, ioe)); } } }
void encoderClose() { if (encoder != null && this.outputStream != null) { try { encoder.close(); } catch (IOException ioe) { this.started = false; addStatus(new ErrorStatus("Failed to write footer for appender named [" + name + "].", this, ioe)); } } }
public void postIOFailure(IOException e) { addStatusIfCountNotOverLimit(new ErrorStatus("IO failure while writing to " + getDescription(), this, e)); presumedClean = false; if (recoveryCoordinator == null) { recoveryCoordinator = new RecoveryCoordinator(); } }
@Test public void smoke() { bsm.add(new ErrorStatus("hello", this)); assertEquals(Status.ERROR, bsm.getLevel()); List<Status> statusList = bsm.getCopyOfStatusList(); assertNotNull(statusList); assertEquals(1, statusList.size()); assertEquals("hello", statusList.get(0).getMessage()); }
@Test public void testNested() { Status s0 = new ErrorStatus("test0", this); Status s1 = new InfoStatus("test1", this); Status s11 = new InfoStatus("test11", this); Status s12 = new InfoStatus("test12", this); s1.add(s11); s1.add(s12); Status s2 = new InfoStatus("test2", this); Status s21 = new InfoStatus("test21", this); Status s211 = new WarnStatus("test211", this); Status s22 = new InfoStatus("test22", this); s2.add(s21); s2.add(s22); s21.add(s211); Context context = new ContextBase(); context.getStatusManager().add(s0); context.getStatusManager().add(s1); context.getStatusManager().add(s2); StatusPrinter.print(context); String result = outputStream.toString(); assertTrue(result.contains("+ INFO in "+this.getClass().getName())); assertTrue(result.contains("+ WARN in "+this.getClass().getName())); assertTrue(result.contains(" |-WARN in "+this.getClass().getName())); }
@Test public void testWithException() { Status s0 = new ErrorStatus("test0", this); Status s1 = new InfoStatus("test1", this, new Exception("testEx")); Status s11 = new InfoStatus("test11", this); Status s12 = new InfoStatus("test12", this); s1.add(s11); s1.add(s12); Status s2 = new InfoStatus("test2", this); Status s21 = new InfoStatus("test21", this); Status s211 = new WarnStatus("test211", this); Status s22 = new InfoStatus("test22", this); s2.add(s21); s2.add(s22); s21.add(s211); Context context = new ContextBase(); context.getStatusManager().add(s0); context.getStatusManager().add(s1); context.getStatusManager().add(s2); StatusPrinter.print(context); String result = outputStream.toString(); assertTrue(result.contains("|-ERROR in "+this.getClass().getName())); assertTrue(result.contains("+ INFO in "+this.getClass().getName())); assertTrue(result.contains("ch.qos.logback.core.util.StatusPrinterTest.testWithException")); }
@Test public void testStopThrowsException() throws Exception { appender.start(); assertTrue(appender.isStarted()); IOException ex = new IOException("test exception"); runner.setStopException(ex); appender.stop(); Status status = context.getLastStatus(); assertNotNull(status); assertTrue(status instanceof ErrorStatus); assertTrue(status.getMessage().contains(ex.getMessage())); assertSame(ex, status.getThrowable()); }
private static void addError(LoggerContext context, Object origin, String msg, Throwable t) { StatusManager sm = context.getStatusManager(); if (sm == null) { return; } sm.add(new ErrorStatus(msg, origin, t)); }
@Test public void testStopThrowsException() throws Exception { receiver.start(); assertTrue(receiver.isStarted()); IOException ex = new IOException("test exception"); runner.setStopException(ex); receiver.stop(); Status status = context.getLastStatus(); assertNotNull(status); assertTrue(status instanceof ErrorStatus); assertTrue(status.getMessage().contains(ex.getMessage())); assertSame(ex, status.getThrowable()); }
@Test public void multipleNesting() throws JoranException { configure(SIFT_FOLDER_PREFIX + "multipleNesting.xml"); logger.debug("hello"); logger.debug("hello"); logger.debug("hello"); Appender<ILoggingEvent> listAppender = getAppenderTracker().find("multipleDefault"); StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); assertNotNull(listAppender); statusChecker.assertContainsMatch(ErrorStatus.ERROR, "Only and only one appender can be nested"); }
public synchronized void setWithJansi(final boolean withJansi) { if (isStarted()) { addStatus(new ErrorStatus("Cannot configure appender named \"" + this.name + "\" after it has been started.", this)); } this.withJansi = withJansi; }