public void start() { if (filename == null) { String tomcatHomeProperty = OptionHelper.getSystemProperty("catalina.home"); filename = tomcatHomeProperty + File.separatorChar + DEFAULT_CONFIG_FILE; getStatusManager() .add(new InfoStatus("filename property not set. Assuming [" + filename + "]", this)); } File configFile = new File(filename); if (configFile.exists()) { try { JoranConfigurator jc = new JoranConfigurator(); jc.setContext(this); jc.doConfigure(filename); } catch (JoranException e) { // TODO can we do better than printing a stack trace on syserr? e.printStackTrace(); } } else { getStatusManager().add(new WarnStatus("[" + filename + "] does not exist", this)); } if (!quiet) { StatusPrinter.print(getStatusManager()); } started = true; }
// A few things that need to get set up before regular init(). @Override protected void internalInit() { log.debug("Starting CWM Application Internal Init"); log.debug("Application Class is " + getClass().getName()); loadAppProperties(); // If using Logback as the logger, and we have a logConfig property, // then read that configuration. File logConfig = configuration.getOptionalFile("cwm.logConfig"); if (logConfig != null && LoggerFactory.getILoggerFactory() instanceof LoggerContext) { log.info("Log Configuration: {}", logConfig); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); // the context was probably already configured by default configuration rules lc.reset(); configurator.doConfigure(logConfig); } catch (JoranException je) { je.printStackTrace(); } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } loadServices(); getComponentInstantiationListeners() .add(new GuiceComponentInjector(this, getInjectionModuleArray())); super.internalInit(); }
public static void main(String[] args) { // TODO: logback must be a compile-time dependency for this to work -> either change that or // comment it out LoggerContext loggerContext = ((ch.qos.logback.classic.Logger) logger).getLoggerContext(); StatusPrinter.print(loggerContext); logger.info("Starting ..."); logger.debug( "Java: {} {} {}", System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home")); logger.debug( "Java VM: {} {} {}", System.getProperty("java.vm.name"), System.getProperty("java.vm.vendor"), System.getProperty("java.vm.version")); logger.debug( "OS: {} {} {}", System.getProperty("os.name"), System.getProperty("os.arch"), System.getProperty("os.version")); logger.debug("Max. Memory: {} MB", Runtime.getRuntime().maxMemory() / (1024 * 1024)); SwingUtilities.invokeLater( new Runnable() { @Override public void run() { createAndShowGUI(); } }); }
@Test public void noAttributes() { propertyAction.begin(ec, null, atts); assertEquals(1, context.getStatusManager().getCount()); assertTrue(checkError()); StatusPrinter.print(context); }
@Test(timeout = 3000L) public void fallbackToSafe_FollowedByRecovery() throws IOException, JoranException, InterruptedException { String path = CoreTestConstants.OUTPUT_DIR_PREFIX + "reconfigureOnChangeConfig_fallbackToSafe-" + diff + ".xml"; File topLevelFile = new File(path); writeToFile( topLevelFile, "<configuration scan=\"true\" scanPeriod=\"5 millisecond\"><root level=\"ERROR\"/></configuration> "); configure(topLevelFile); CountDownLatch changeDetectedLatch = waitForReconfigurationToBeDone(null); ReconfigureOnChangeTask oldRoct = getRegisteredReconfigureTask(); assertNotNull(oldRoct); writeToFile( topLevelFile, "<configuration scan=\"true\" scanPeriod=\"5 millisecond\">\n" + " <root></configuration>"); changeDetectedLatch.await(); statusChecker.assertContainsMatch(Status.WARN, FALLING_BACK_TO_SAFE_CONFIGURATION); statusChecker.assertContainsMatch(Status.INFO, RE_REGISTERING_PREVIOUS_SAFE_CONFIGURATION); loggerContext.getStatusManager().clear(); CountDownLatch secondDoneLatch = waitForReconfigurationToBeDone(oldRoct); writeToFile( topLevelFile, "<configuration scan=\"true\" scanPeriod=\"5 millisecond\"><root level=\"ERROR\"/></configuration> "); secondDoneLatch.await(); StatusPrinter.print(loggerContext); statusChecker.assertIsErrorFree(); statusChecker.containsMatch(DETECTED_CHANGE_IN_CONFIGURATION_FILES); }
public static void load(String location) throws IOException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); File externalConfigFile = new File(location); if (!externalConfigFile.exists()) { throw new IOException( "Logback External Conf File Parameter does not reference a file that exists"); } else { if (!externalConfigFile.isFile()) { throw new IOException( "Logback External Conf File Parameter exists, but does not reference a file"); } else { if (!externalConfigFile.canRead()) { throw new IOException( "Logback External Conf File exists and is a file, but cannot be read."); } else { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(location); } catch (JoranException e) { throw new RuntimeException(e); } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } } } }
public synchronized void init() { if (isInit == true) throw new RuntimeException("LogbackFactory had init~~~"); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { File externalConfigFile = new File(fileName); if (!externalConfigFile.exists()) { throw new IOException("logback server file : " + fileName + " not existed!!!"); } if (!externalConfigFile.isFile()) { throw new IOException("logback server file : " + fileName + " not file!!!"); } if (!externalConfigFile.canRead()) { throw new IOException("logback server file : " + fileName + " can't read!!!"); } JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(fileName); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } catch (final Exception e) { e.printStackTrace(); } isInit = true; }
@Test public void testAppendLoggingEvent() throws SQLException { ILoggingEvent event = createLoggingEvent(); appender.append(event); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); Statement stmt = connectionSource.getConnection().createStatement(); ResultSet rs = null; rs = stmt.executeQuery("SELECT * FROM logging_event"); if (rs.next()) { assertEquals(event.getTimeStamp(), rs.getLong(DBAppender.TIMESTMP_INDEX)); assertEquals(event.getFormattedMessage(), rs.getString(DBAppender.FORMATTED_MESSAGE_INDEX)); assertEquals(event.getLoggerName(), rs.getString(DBAppender.LOGGER_NAME_INDEX)); assertEquals(event.getLevel().toString(), rs.getString(DBAppender.LEVEL_STRING_INDEX)); assertEquals(event.getThreadName(), rs.getString(DBAppender.THREAD_NAME_INDEX)); assertEquals( DBHelper.computeReferenceMask(event), rs.getShort(DBAppender.REFERENCE_FLAG_INDEX)); assertEquals(String.valueOf(diff), rs.getString(DBAppender.ARG0_INDEX)); StackTraceElement callerData = event.getCallerData()[0]; assertEquals(callerData.getFileName(), rs.getString(DBAppender.CALLER_FILENAME_INDEX)); assertEquals(callerData.getClassName(), rs.getString(DBAppender.CALLER_CLASS_INDEX)); assertEquals(callerData.getMethodName(), rs.getString(DBAppender.CALLER_METHOD_INDEX)); } else { fail("No row was inserted in the database"); } rs.close(); stmt.close(); }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(HelloWorld2.class); logger.debug("Hello world."); // print internal state LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger("chapters.introduction.HelloWorld2"); logger.debug("Hello world."); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); }
@Test public void somekeReplace() { pl.setPattern("%replace(a1234b){'\\d{4}', 'XXXX'}"); pl.start(); StatusPrinter.print(lc); String val = pl.doLayout(getEventObject()); assertEquals("aXXXXb", val); }
@Test public void basic() throws InterruptedException { configure(); String logMsg = "hello 1"; logger.debug(logMsg); StatusPrinter.print(lc); }
@Test public void tException() throws InterruptedException { configure(); String logMsg = "hello 2"; String exMsg = " just testing"; Exception ex = new Exception(exMsg); logger.debug(logMsg, ex); StatusPrinter.print(lc); }
private void executeHarness(int duration, boolean withDelay) throws InterruptedException { MultiThreadedHarness multiThreadedHarness = new MultiThreadedHarness(duration); this.runnableArray = buildRunnableArray(withDelay); multiThreadedHarness.execute(runnableArray); StatusChecker checker = new StatusChecker(context.getStatusManager()); if (!checker.isErrorFree(0)) { StatusPrinter.print(context); fail("errors reported"); } }
public static void main(String[] args) { // assume SLF4J is bound to logback in the current environment LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); // print logback's internal status StatusPrinter.print(lc); logger.info("Entering application."); Foo foo = new Foo(); foo.doIt(); logger.info("Exiting application."); }
@Test public void testNoStart() { Appender<E> appender = getAppender(); appender.setContext(context); appender.setName("doh"); // is null OK? appender.doAppend(null); StatusChecker checker = new StatusChecker(context.getStatusManager()); StatusPrinter.print(context); assertTrue(checker.containsMatch("Attempted to append to non started appender \\[doh\\].")); }
/** Initializes the logger. */ private static void initLogger() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(InspectIT.class.getResourceAsStream("/config/logback.xml")); } catch (JoranException je) { // NOPMD NOCHK StatusPrinter will handle this NOCHK } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
public static void main(String[] args) { System.out.println("Hello World!"); logger.error("error"); logger.warn("warning"); logger.info("info"); logger.debug("debug"); logger.trace("trace"); // print internal state LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); StatusPrinter.print(lc); }
@Test public void replaceWithJoran() throws JoranException { configure(ClassicTestConstants.JORAN_INPUT_PREFIX + "pattern/replace0.xml"); StatusPrinter.print(lc); root.getAppender("LIST"); String msg = "And the number is 4111111111110000, expiring on 12/2010"; logger.debug(msg); StringListAppender<ILoggingEvent> sla = (StringListAppender<ILoggingEvent>) root.getAppender("LIST"); assertNotNull(sla); assertEquals(1, sla.strList.size()); assertEquals("And the number is XXXX, expiring on 12/2010", sla.strList.get(0)); }
@Test public void LBCLASSIC_50() throws JoranException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(ClassicTestConstants.JORAN_INPUT_PREFIX + "syslog_LBCLASSIC_50.xml"); org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); logger.info("hello"); StatusPrinter.print(lc); }
@Test public void large() throws InterruptedException { configure(); StringBuilder largeBuf = new StringBuilder(); for (int i = 0; i < 2 * 1024 * 1024; i++) { largeBuf.append('a'); } logger.debug(largeBuf.toString()); String logMsg = "hello 3"; logger.debug(logMsg); Thread.sleep(RecoveryCoordinator.BACKOFF_COEFFICIENT_MIN + 10); logger.debug(logMsg); StatusPrinter.print(lc); }
@Override protected void configure(String logFile) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); lc.putProperty("se.trillian.goodies.hostname", getHostName()); lc.putProperty("se.trillian.goodies.hostname.full", getFullHostName()); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); configurator.doConfigure(logFile); } catch (JoranException je) { StatusPrinter.print(lc); } }
void doEvaluateAndCheck(String expression, ILoggingEvent event, boolean expected) throws EvaluationException { gee.setExpression(expression); gee.start(); StatusPrinter.printInCaseOfErrorsOrWarnings(context); assertTrue(statusChecker.isErrorFree(0)); ContextUtil contextUtil = new ContextUtil(context); contextUtil.addGroovyPackages(context.getFrameworkPackages()); contextUtil.addFrameworkPackage( context.getFrameworkPackages(), "ch.qos.logback.classic.boolex"); boolean result = gee.evaluate(event); assertEquals(expected, result); }
void genericTest( String testId, String patternPrefix, String compressionSuffix, boolean fileOptionIsSet, int waitDuration) throws IOException { boolean withCompression = compressionSuffix.length() > 0; String fileName = fileOptionIsSet ? testId2FileName(testId) : null; initRFA(rfa1, fileName); String fileNamePatternStr = randomOutputDir + patternPrefix + "-%d{" + DATE_PATTERN_WITH_SECONDS + "}" + compressionSuffix; initTRBP(rfa1, tbrp1, fileNamePatternStr, currentTime); // compute the current filename addExpectedFileName_ByDate(fileNamePatternStr, getMillisOfCurrentPeriodsStart()); incCurrentTime(1100); tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); for (int i = 0; i < 3; i++) { rfa1.doAppend("Hello---" + i); addExpectedFileNamedIfItsTime_ByDate(fileNamePatternStr); incCurrentTime(500); tbrp1.timeBasedFileNamingAndTriggeringPolicy.setCurrentTime(currentTime); if (withCompression) waitForCompression(tbrp1); } rfa1.stop(); if (waitDuration != NO_RESTART) { doRestart(testId, patternPrefix, fileOptionIsSet, waitDuration); } massageExpectedFilesToCorresponToCurrentTarget(fileName, fileOptionIsSet); StatusPrinter.print(context); rolloverChecker.check(expectedFilenameList); }
public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(MyAppWithConfigFile.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); lc.reset(); configurator.setContext(lc); configurator.doConfigure(args[0]); } catch (JoranException je) { StatusPrinter.print(lc.getStatusManager()); } logger.info("Entering application."); Bar bar = new Bar(); bar.doIt(); logger.info("Exiting application."); }
// See also http://jira.qos.ch/browse/LOGBACK-338 @Test(timeout = 4000L) public void reconfigurationIsNotPossibleInTheAbsenceOfATopFile() throws IOException, JoranException, InterruptedException { String configurationStr = "<configuration scan=\"true\" scanPeriod=\"50 millisecond\"><include resource=\"asResource/inner1.xml\"/></configuration>"; configure(new ByteArrayInputStream(configurationStr.getBytes("UTF-8"))); ConfigurationWatchList configurationWatchList = ConfigurationWatchListUtil.getConfigurationWatchList(loggerContext); assertNull(configurationWatchList); // assertNull(configurationWatchList.getMainURL()); statusChecker.containsMatch(Status.WARN, "Due to missing top level"); StatusPrinter.print(loggerContext); ReconfigureOnChangeTask roct = getRegisteredReconfigureTask(); assertNull(roct); assertEquals(0, loggerContext.getScheduledFutures().size()); }
private void configureFileLogger() { final File logFile = new File(logsDir, DEFAULT_LOG_FILENAME); final RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>(); fileAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); fileAppender.setName(LOG_APPENDER); fileAppender.setFile(logFile.getAbsolutePath()); fileAppender.setEncoder(createEncoder()); fileAppender.setRollingPolicy(createRollingPolicy(fileAppender)); fileAppender.setTriggeringPolicy(createTriggeringPolicy()); fileAppender.start(); final ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("ROOT"); logger.addAppender(fileAppender); StatusPrinter.print((LoggerContext) LoggerFactory.getILoggerFactory()); }
private String handleLogger(CommandLine commandline, boolean gotConfig) { String name = null; String logPath = null; if (!logToFile) { if (gotConfig) { logPath = properties.getProperty(LogFilePathKey); StrH.ttl(initsb, 1, LogFilePathKey, " = ", logPath); if (logPath != null) { System.setProperty(LogFilePathKey, logPath); String base = logPath; int idx = logPath.lastIndexOf('.'); if (idx != -1) base = logPath.substring(0, idx); StrH.ttl(initsb, 1, LogFileBaseKey, " = ", base); System.setProperty(LogFileBaseKey, logPath); name = StrH.getAtomicNameFromPath(base); } } } else { logPath = commandline.getOptionValue(LoggerNameShortCl, DefaultLogPath); StrH.ttl(initsb, 1, "--", LoggerNameLongCl, " = ", logPath); System.setProperty(LogFilePathKey, logPath); String base = logPath; int idx = logPath.lastIndexOf('.'); if (idx != -1) base = logPath.substring(0, idx); StrH.ttl(initsb, 1, LogFileBaseKey, " = ", base); System.setProperty(LogFileBaseKey, logPath); name = StrH.getAtomicNameFromPath(base); } log = LoggerFactory.getLogger(getClass()); if (log.isDebugEnabled()) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); // TODO: StatusPrinter.setPrintStream StatusPrinter.print(lc); try { ClassInfo classInfo = ClassInfo.getInfo(DOF.class); StrH.ttl(initsb, 1, "OAL JAR", " = ", classInfo.getLocation().toExternalForm()); } catch (Exception e) { StrH.ttl(initsb, 1, "OAL JAR", " = null"); } } return name; }
// check for deadlocks @Test(timeout = 4000L) public void scan_LOGBACK_474() throws JoranException, IOException, InterruptedException { loggerContext.setName("scan_LOGBACK_474"); File file = new File(SCAN_LOGBACK_474_FILE_AS_STR); // StatusListenerConfigHelper.addOnConsoleListenerInstance(loggerContext, new // OnConsoleStatusListener()); configure(file); // ReconfigureOnChangeTask roct = waitForReconfigureOnChangeTaskToRun(); int expectedResets = 2; Harness harness = new Harness(expectedResets); RunnableWithCounterAndDone[] runnableArray = buildRunnableArray(file, UpdateType.TOUCH); harness.execute(runnableArray); loggerContext.getStatusManager().add(new InfoStatus("end of execution ", this)); StatusPrinter.print(loggerContext); checkResetCount(expectedResets); }
@Test public void failed_rename() throws IOException { if (!EnvUtilForTests.isWindows()) return; FileOutputStream fos = null; try { String fileName = testId2FileName("failed_rename"); File file = new File(fileName); file.getParentFile().mkdirs(); fos = new FileOutputStream(fileName); String testId = "failed_rename"; rolloverChecker = new ZRolloverChecker(testId); genericTest(testId, "failed_rename", "", FILE_OPTION_SET, NO_RESTART); } finally { StatusPrinter.print(context); if (fos != null) fos.close(); } }