@Test public void testUdpSender() throws JoranException, InterruptedException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog-udp.xml")); Logger logger = context.getLogger("test-udp"); logger.info("test message over udp"); context.stop(); Thread.sleep(100); final String serverData = serverStream.toString(); assertTrue("Server received: " + serverData, serverData.contains("test message over udp")); }
public static void load(String externalConfigFileLocation) throws IOException, JoranException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); File externalConfigFile = new File(externalConfigFileLocation); if (!externalConfigFile.exists()) { throw new IOException("Logback External Config File Parameter does not reference a file that exists"); } else { if (!externalConfigFile.isFile()) { throw new IOException("Logback External Config File Parameter exists, but does not reference a file"); } else { if (!externalConfigFile.canRead()) { throw new IOException("Logback External Config File exists and is a file, but cannot be read."); } else { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(externalConfigFileLocation); StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } } } }
public static void initLog() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator jc = new JoranConfigurator(); jc.setContext(context); context.reset(); String env = System.getProperty("system.environment"); if(StringUtils.isBlank(env)) { System.err.println("get system.environment error"); throw new RuntimeException("can't get env, service stop!"); } URL tmpConfigFIleStr = Startup.class.getResource("/logback-" + env + ".xml"); try { System.out.println("start with configFile : " + tmpConfigFIleStr); jc.doConfigure(tmpConfigFIleStr); log.info("load logback config --> " + tmpConfigFIleStr.getFile()); } catch (JoranException e) { System.err.println(tmpConfigFIleStr + " not exist"); throw new RuntimeException(e); } }
@Test public void testTcpSender() throws JoranException, InterruptedException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog-tcp.xml")); Logger logger = context.getLogger("test-tcp"); logger.info("test message over tcp"); context.stop(); Thread.sleep(100); final String serverData = serverStream.toString(); assertTrue("Server received: " + serverData, serverData.contains("test message over tcp")); }
@Test public void testTlsSender() throws JoranException, InterruptedException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(this.getClass().getClassLoader().getResourceAsStream("logback-syslog-tls.xml")); Logger logger = context.getLogger("test-tls"); logger.info("test message over tls"); context.stop(); Thread.sleep(100); final String serverData = serverStream.toString(); assertTrue("Server received: " + serverData, serverData.contains("test message over tls")); }
@PostConstruct public void initializeLogback() { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); InputStream is = InitLogback.class.getClassLoader().getResourceAsStream("tasfe-logback.xml"); if (is == null) return; JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(is); } catch (JoranException e) { e.printStackTrace(); } }
protected void captureOutput() throws IOException, JoranException { System.setProperty("ROOT_APPENDER", "JSON_CONSOLE"); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("logback.xml"); configurator.setContext(loggerContext); configurator.doConfigure(configStream); configStream.close(); baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setOut(ps); }
@Test public void testDefaultOutputWithBadException() throws JoranException, IOException { configLogback(LOGBACK_WITH_THREAD); String message = "test output with bad exception"; log.error(message, new InvalidClassException("Class null is invalid")); String logger = AbstractLoggingException.class.getCanonicalName(); String errorClass = InvalidClassException.class.getCanonicalName(); String message2 = String.format("Bad implementation of '%s' in use", errorClass); String output = baos.toString(); // there must be original log assertThat(output).containsPattern( DEFAULT_DATE_FORMAT + ERROR + getThreadName() + getLogger() + message + "\n" ); // alongside log about alert level misuse assertThat(output).containsPattern( DEFAULT_DATE_FORMAT + ERROR + getThreadName() + logger + ":\\d+: \\[P1\\] 0. " + message2 + "\n" ); }
@Test public void testOutputForOptionalErrorValues() throws JoranException, IOException { configLogback(LOGBACK_WITH_CUSTOM_DATE_FORMAT); String message = "test alert level and error code for regular log level"; log.info(message); log.info(message, new DummyP3Exception()); String timestamp = "\\d{2}-\\d{2}-\\d{4}"; String logger = this.getClass().getCanonicalName(); String output = baos.toString(); assertThat(output).containsPattern( timestamp + INFO + logger + ":\\d+: " + message + "\n" ); assertThat(output).containsPattern( timestamp + INFO + logger + ":\\d+: \\[P3\\] 0. " + message + "\n" ); }
@Test public void testStacktraceExistsAfterTheLogEntry() throws JoranException, IOException { configLogback(LOGBACK); String message = "test stacktrace"; log.error(message, new DummyP2Exception()); String logger = this.getClass().getCanonicalName(); assertThat(baos.toString()).containsPattern( DEFAULT_DATE_FORMAT + ERROR + getThreadName() + logger + ":\\d+: \\[P2\\] 0. " + message + "\n" + "\tat " + logger + ".testStacktraceExists(.*" + this.getClass().getSimpleName() + ".java:\\d+.*)\n" ); log.error(message, new DummyP2Exception(new ArithmeticException("There is no such operation ':'"))); assertThat(baos.toString()).containsPattern( "Caused by: " + ArithmeticException.class.getCanonicalName() + ": There is no such operation ':'\n" ); }
private void writeLogsOnFileAndConsole() { loggers.debug("****Configuring Logger****"); try { if(Platform.isRunning()){ System.setProperty(HYDROGRAPH_INSTALLATION_LOCATION, Platform.getInstallLocation().getURL().getPath()); ClassLoader loader = new URLClassLoader(new URL[] {new File(Platform.getInstallLocation().getURL().getPath() + LOG_DIR).toURI().toURL()}); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); URL url = Loader.getResource(CLASSIC_FILE, loader); if (url != null) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(url); lc.start(); } loggers.debug("****Logger Configured Successfully****"); } } catch(MalformedURLException|JoranException exception){ loggers.error("Failed to configure the logger {}", exception); } }
private void initializeLogging() { String graviteeHome = System.getProperty("gravitee.home"); String logbackConfiguration = graviteeHome + File.separator + "config" + File.separator + "logback.xml"; File logbackConfigurationfile = new File(logbackConfiguration); // If logback configuration available, load it, else, load default logback configuration if (logbackConfigurationfile.exists()) { System.setProperty("logback.configurationFile", logbackConfigurationfile.getAbsolutePath()); StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton(); LoggerContext loggerContext = (LoggerContext) loggerBinder.getLoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(logbackConfigurationfile); } catch( JoranException e ) { e.printStackTrace(); } // Internal status data is printed in case of warnings or errors. StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } }
void init() { try { try { (new KonkerContextInitializer(this.defaultLoggerContext)).autoConfig(); } catch (JoranException var2) { Util.report("Failed to auto configure default logger context", var2); } if(!StatusUtil.contextHasStatusListener(this.defaultLoggerContext)) { StatusPrinter.printInCaseOfErrorsOrWarnings(this.defaultLoggerContext); } this.contextSelectorBinder.init(this.defaultLoggerContext, KEY); this.initialized = true; } catch (Throwable var3) { Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", var3); } }
public void autoConfig() throws JoranException { KonkerStatusListenerConfigHelper.installIfAsked(this.loggerContext); URL url = this.findURLOfDefaultConfigurationFile(true); if (url != null) { this.configureByResource(url); } else { KonkerLoggerConfigurator c = (KonkerLoggerConfigurator) EnvUtil.loadFromServiceLoader(KonkerLoggerConfigurator.class); if (c != null) { try { c.setContext(this.loggerContext); c.configure(this.loggerContext); } catch (Exception var4) { throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", new Object[]{c != null ? c.getClass().getCanonicalName() : "null"}), var4); } } else { KonkerLoggerBasicConfigurator.configure(this.loggerContext); } } }
@Override public void contextInitialized(ServletContextEvent arg0) { String dir = getConfigPath(); LOG.debug("リソースパス:{}", dir); if (StringUtils.isEmpty(dir)) { LOG.info("リソースパスが定義されていないためデフォルトのログ出力設定を使用します"); return; } try { new LogbackConfigurationLoader().load( Paths.get(dir, "logback.xml").toFile(), Paths.get(dir, "logback.groovy").toFile()); } catch (JoranException e) { LOG.warn("ログ出力設定に失敗しました。デフォルトのログ出力設定を使用します"); } }
public void load(File... configList) throws JoranException { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); for (File config : configList) { if (config.exists()) { if (config.isFile()) { if (config.canRead()) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); // 設定をクリアして再読み込み context.reset(); configurator.doConfigure(config); LOG.warn("logback設定ファイル再設定が完了しました。{}", config.getAbsolutePath()); break; } else { LOG.warn("logback設定ファイルが読み込めません。{}", config.getAbsolutePath()); } } else { LOG.warn("logback設定ファイルがディレクトリです。{}", config.getAbsolutePath()); } } else { LOG.info("logback設定ファイルが見つかりません。{}", config.getAbsolutePath()); } } }
/** * Initialize logback from the given file location, with no config file * refreshing. Assumes an XML file in case of a ".xml" file extension, and a * properties file otherwise. * * @param location the location of the config file: either a "classpath:" * location (e.g. "classpath:mylogback.properties"), an absolute * file URL (e.g. * "file:C:/logback.properties), or a plain absolute path in the file system (e.g. " * C:/logback.properties") * @throws FileNotFoundException if the location specifies an invalid file path */ public static void initLogging(String location) throws FileNotFoundException { String resolvedLocation = SystemPropertyUtils .resolvePlaceholders(location); URL url = ResourceUtils.getURL(resolvedLocation); if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) { // DOMConfigurator.configure(url); configurator.setContext(lc); lc.reset(); try { configurator.doConfigure(url); } catch (JoranException ex) { throw new FileNotFoundException(url.getPath()); } lc.start(); } // else { // PropertyConfigurator.configure(url); // } }
private void initializeLogback() { Path logbackFilePath = Paths.get(configPath, "logback.xml"); if (logbackFilePath.toFile().exists()) { try { // Load logback configuration LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); configurator.doConfigure(logbackFilePath.toFile()); // Install java.util.logging bridge SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); } catch (JoranException e) { throw new GossipInitializeException("Misconfiguration on logback.xml, check it.", e); } } }
private static void configureLogger(String logDir, String logLevel, String logbackConf) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); if (!logDir.endsWith(File.separator)) logDir+= File.separator; context.putProperty("LOG_DIR", logDir); context.putProperty("LOG_LEVEL", logLevel); InputStream is = classloader.getResourceAsStream(logbackConf); configurator.doConfigure(is); } catch (JoranException je) { LOG.warn("Cannot configure logger. Continue to execute the command.", je); } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
@Override public void onApplicationEvent(ApplicationEvent event) { final String settings = environment.getProperty("logging.config.src"); if (StringUtils.hasText(settings)) { try { final ContextBase context = (ContextBase) StaticLoggerBinder.getSingleton().getLoggerFactory(); final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); LOG.info("try to update logback configuration to {}", settings); context.reset(); configurator.doConfigure(new ByteArrayInputStream(settings.getBytes())); } catch (JoranException e) { LOG.error("can't load settings", e); } } }
/** * Loads the Logback configuration from a resource file. * Only here to avoid polluting other examples with logs. Could be * replaced by a simple logback.xml file in the resource folder. */ private static void loadLoggerConfiguration() { LoggerContext context = (LoggerContext) LoggerFactory .getILoggerFactory(); context.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); try { if (LOGBACK_CONF_FILE != null) { configurator.doConfigure(LOGBACK_CONF_FILE); } } catch (JoranException e) { Logger.getLogger(MainTrader.class.getName()).log(Level.SEVERE, "Unable to load Logback configuration", e); } }
private static void configureLogbackFromLocalFile() { boolean localLogFileExists = Files.exists(Paths.get("./logback.xml")); if (!localLogFileExists) { System.out.println("logback.xml not found in local path - defaulting to packaged one"); return; } // assume SLF4J is bound to logback in the current environment LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); // Call context.reset() to clear any previous configuration, e.g. default // configuration. For multi-step configuration, omit calling context.reset(). context.reset(); configurator.doConfigure("./logback.xml"); } catch (JoranException je) { // StatusPrinter will handle this } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
public void doTest(String configFile) throws JoranException { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); configurator.doConfigure(configFile); Appender<IAccessEvent> appender = context.getAppender("DB"); for (int i = 0; i < 10; i++) { IAccessEvent event = DummyAccessEventBuilder.buildNewAccessEvent(); appender.doAppend(event); } StatusPrinter.print(context); // check that there were no errors assertEquals(Status.INFO, statusChecker.getHighestLevel(0)); }
@Test public void timeoutPropertyShouldBeHonored() throws JoranException, InterruptedException { configure(SIFT_FOLDER_PREFIX + "timeout.xml"); long timeout = 30*1000; SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "timeout", null, null); event.setTimeStamp(now); sa.doAppend(event); AppenderTracker<ILoggingEvent> tracker = sa.getAppenderTracker(); assertEquals(1, tracker.getComponentCount()); now += timeout+1; tracker.removeStaleComponents(now); assertEquals(0, tracker.getComponentCount()); statusChecker.assertIsErrorFree(); }
private void initializeLogging() { String graviteeHome = System.getProperty("gravitee.home"); String logbackConfiguration = graviteeHome + File.separator + "config" + File.separator + "logback.xml"; File logbackConfigurationfile = new File(logbackConfiguration); // If logback configuration available, load it, else, load default logback configuration if (logbackConfigurationfile.exists()) { System.setProperty("logback.configurationFile", logbackConfigurationfile.getAbsolutePath()); StaticLoggerBinder loggerBinder = StaticLoggerBinder.getSingleton(); LoggerContext loggerContext = (LoggerContext) loggerBinder.getLoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); try { configurator.doConfigure(logbackConfigurationfile); } catch( JoranException e ) { LoggerFactory.getLogger(Container.class).error("An error occurs while initializing logging system", e); } // Internal status data is printed in case of warnings or errors. StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } }
@Test public void sessionFinalizationShouldCauseLingering() throws JoranException { String mdcKey = "linger"; String mdcVal = "session" + diff; configure(SIFT_FOLDER_PREFIX + "lingering.xml"); MDC.put(mdcKey, mdcVal); logger.debug("linger 1"); logger.debug(ClassicConstants.FINALIZE_SESSION_MARKER, "linger 2"); long now = System.currentTimeMillis(); SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); AppenderTracker<ILoggingEvent> tracker = sa.getAppenderTracker(); assertEquals(1, tracker.allKeys().size()); Appender<ILoggingEvent> appender = tracker.find(mdcVal); assertTrue(appender.isStarted()); tracker.removeStaleComponents(now + AppenderTracker.LINGERING_TIMEOUT + 1); // previously lingering appenders should be closed upon timeout assertFalse(appender.isStarted()); // and they should be gone assertEquals(0, tracker.allKeys().size()); }
public static void main(String[] args) { Logger logger = LoggerFactory .getLogger(GoMDC.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure("mdcFilter.xml"); } catch (JoranException je) { StatusPrinter.print(lc); } logger.debug("I know me " + 0); MDC.put("key", "val"); logger.debug("I know me " + 1); StatusPrinter.print(lc); }
@Test public void properties() throws JoranException { String configFileAsStr = ClassicTestConstants.JORAN_INPUT_PREFIX + "properties.xml"; assertNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); assertNull(System.getProperty("sys")); configure(configFileAsStr); assertNotNull(loggerContext.getProperty(CoreConstants.HOSTNAME_KEY)); assertNull(loggerContext.getProperty("transientKey1")); assertNull(loggerContext.getProperty("transientKey2")); assertEquals("node0", loggerContext.getProperty("nodeId")); assertEquals("tem", System.getProperty("sys")); assertNotNull(loggerContext.getProperty("path")); checker.assertIsErrorFree(); }
@Test public void lbcore127() throws IOException, JoranException { String jarEntry = "buzz.xml"; String jarEntry2 = "lightyear.xml"; File jarFile = makeRandomJarFile(); fillInJarFile(jarFile, jarEntry, jarEntry2); URL url1 = asURL(jarFile, jarEntry); URL url2 = asURL(jarFile, jarEntry2); URLConnection urlConnection2 = url2.openConnection(); urlConnection2.setUseCaches(false); InputStream is = urlConnection2.getInputStream(); TrivialConfigurator tc = new TrivialConfigurator(rulesMap); tc.setContext(context); tc.doConfigure(url1); is.read(); is.close(); // deleting an open file fails assertTrue(jarFile.delete()); assertFalse(jarFile.exists()); }
/** * Tests a Logback-access configuration exception in the case where the test spring configuration file is invalid. */ @Test public void logbackAccessConfigurationExceptionWhereTestSpringConfigurationFileIsInvalid() { Map<String, Object> properties = new HashMap<>(); properties.put("server.port", findAvailableTcpPort()); SpringApplication application = new SpringApplication(contextConfiguration); application.setDefaultProperties(properties); Throwable throwable = catchThrowable(application::run); Optional<LogbackAccessConfigurationException> exc = findLogbackAccessConfigurationException(throwable); assertThat(exc).hasValueSatisfying(value -> assertThat(value) .hasMessageStartingWith("Could not configure Logback-access:") .hasMessageContaining("config=[classpath:logback-access-test-spring.xml]") .hasCauseInstanceOf(JoranException.class) ); }
@Test public void testBasic() throws JoranException { ListenAction listenAction = new ListenAction(); rulesMap.put(new ElementSelector("fire"), listenAction); TrivialConfigurator gc = new TrivialConfigurator(rulesMap); gc.setContext(context); gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); //for(SaxEvent se: listenAction.getSeList()) { // System.out.println(se); //} assertEquals(5, listenAction.getSeList().size()); assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); }
@Test public void testReplay() throws JoranException { ListenAction listenAction = new ListenAction(); rulesMap.put(new ElementSelector("fire"), listenAction); TrivialConfigurator gc = new TrivialConfigurator(rulesMap); gc.setContext(context); gc.doConfigure(CoreTestConstants.TEST_SRC_PREFIX + "input/joran/fire1.xml"); // for(SaxEvent se: listenAction.getSeList()) { // System.out.println(se); // } assertEquals(5, listenAction.getSeList().size()); assertTrue(listenAction.getSeList().get(0) instanceof StartEvent); assertTrue(listenAction.getSeList().get(1) instanceof StartEvent); assertTrue(listenAction.getSeList().get(2) instanceof BodyEvent); assertTrue(listenAction.getSeList().get(3) instanceof EndEvent); }
public static void main(String[] args) throws Exception { Map<ElementSelector, Action> ruleMap = new HashMap<ElementSelector, Action>(); // Note the wild card character '*', in the paterns, signifying any level // of nesting. ruleMap.put(new ElementSelector("*/computation"), new ComputationAction2()); ruleMap.put(new ElementSelector("*/computation/literal"), new LiteralAction()); ruleMap.put(new ElementSelector("*/computation/add"), new AddAction()); ruleMap.put(new ElementSelector("*/computation/multiply"), new MultiplyAction()); Context context = new ContextBase(); SimpleConfigurator simpleConfigurator = new SimpleConfigurator(ruleMap); // link the configurator with its context simpleConfigurator.setContext(context); try { simpleConfigurator.doConfigure(args[0]); } catch (JoranException e) { // Print any errors that might have occured. StatusPrinter.print(context); } }
/** * Package access for testing purposes. */ void init() { try { try { new ContextInitializer(defaultLoggerContext).autoConfig(); } catch (JoranException je) { Util.report("Failed to auto configure default logger context", je); } // logback-292 if(!StatusUtil.contextHasStatusListener(defaultLoggerContext)) { StatusPrinter.printInCaseOfErrorsOrWarnings(defaultLoggerContext); } contextSelectorBinder.init(defaultLoggerContext, KEY); initialized = true; } catch (Throwable t) { // we should never get here Util.report("Failed to instantiate [" + LoggerContext.class.getName() + "]", t); } }
public void reloadByFileName(String fileName) throws JoranException, FileNotFoundException { File f = new File(fileName); if (f.exists() && f.isFile()) { URL url; try { url = f.toURI().toURL(); reloadByURL(url); } catch (MalformedURLException e) { throw new RuntimeException( "Unexpected MalformedURLException occured. See nexted cause.", e); } } else { String errMsg = "Could not find [" + fileName + "]"; addInfo(errMsg); throw new FileNotFoundException(errMsg); } }
public void reloadByURL(URL url) throws JoranException { StatusListenerAsList statusListenerAsList = new StatusListenerAsList(); addStatusListener(statusListenerAsList); addInfo("Resetting context: " + loggerContext.getName()); loggerContext.reset(); // after a reset the statusListenerAsList gets removed as a listener addStatusListener(statusListenerAsList); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(url); addInfo("Context: " + loggerContext.getName() + " reloaded."); } finally { removeStatusListener(statusListenerAsList); if (debug) { StatusPrinter.print(statusListenerAsList.getStatusList()); } } }
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"); } }
public void autoConfig() throws JoranException { StatusListenerConfigHelper.installIfAsked(loggerContext); URL url = findURLOfDefaultConfigurationFile(true); if (url != null) { configureByResource(url); } else { Configurator c = EnvUtil.loadFromServiceLoader(Configurator.class); if (c != null) { try { c.setContext(loggerContext); c.configure(loggerContext); } catch (Exception e) { throw new LogbackException(String.format("Failed to initialize Configurator: %s using ServiceLoader", c != null ? c.getClass().getCanonicalName() : "null"), e); } } else { BasicConfigurator.configure(loggerContext); } } }
@Test public void maxAppendersCountPropertyShouldBeHonored() throws JoranException { configure(SIFT_FOLDER_PREFIX + "maxAppenderCount.xml"); int max = 5; SiftingAppender sa = (SiftingAppender) root.getAppender("SIFT"); String mdcKey = "max"; for(int i = 0; i <= max; i++) { MDC.put(mdcKey, "" + (diff + i)); LoggingEvent event = new LoggingEvent("", logger, Level.DEBUG, "max"+i, null, null); event.setTimeStamp(now); sa.doAppend(event); now += AbstractComponentTracker.WAIT_BETWEEN_SUCCESSIVE_REMOVAL_ITERATIONS; } AppenderTracker<ILoggingEvent> tracker = sa.getAppenderTracker(); assertEquals(max, tracker.allKeys().size()); assertNull(tracker.find("" + (diff + 0))); for(int i = 1; i <= max; i++) { assertNotNull(tracker.find("" + (diff + i))); } }