@Test public void testLoggingContextReset() { addYesFilter(); assertNotNull(context.getTurboFilterList().get(0)); context.reset(); assertEquals(0, context.getTurboFilterList().size()); }
// 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(); }
@Override public void contextInitialized(final ServletContextEvent servletContextEvent) { final ServletContext sc = servletContextEvent.getServletContext(); final String logbackConfigLocation = sc.getInitParameter(LOGBACK_CONFIG_LOCATION); String filePath = null; try { final Path configFile = Paths.get(sc.getResource(logbackConfigLocation).toURI()); filePath = configFile.toAbsolutePath().toString(); final File rootFolder = new File(sc.getResource("/").getPath()); final File logFolder = new File(rootFolder.getParentFile().getPath() + "/logs"); if (!logFolder.exists()) { if (!logFolder.mkdirs()) { throw new IOException("Cannot create: " + logFolder.getAbsolutePath()); } } System.setProperty("log.basepath", logFolder.getAbsolutePath()); final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); final JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(configFile.toFile()); } catch (Exception e) { System.err.println("Failed to locate logback config file: " + filePath); return; } System.out.println("[INFO] Init logback by the config file:" + filePath); }
public static void enableLogging(boolean enable) { // get the context LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); try { // create a new configurator JoranConfigurator configurator = new JoranConfigurator(); // set context and reset it configurator.setContext(loggerContext); loggerContext.reset(); // if logging should be enabled if (enable) { // add the correct properties and load the XML file loggerContext.putProperty("araraLogName", AraraConstants.LOGNAME); configurator.doConfigure( AraraLogging.class.getResourceAsStream("/com/github/arara/conf/logback.xml")); } } catch (JoranException joranException) { // do nothing } }
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; }
/** * Initialize logback from the given URL. * * @param url the url pointing to the location of the config file. * @throws JoranException if the url points to a non existing location or an error occurs during * the parsing operation. */ public static void initLogging(URL url) throws JoranException { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); loggerContext.reset(); configurator.doConfigure(url); }
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 void testAspects() throws Exception { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); // the context was probably already configured by default configuration // rules lc.reset(); configurator.doConfigure(getClass().getResource("logback.xml")); ListAppender<LoggingEvent> listAppender = (ListAppender<LoggingEvent>) lc.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("listAppender"); ProfiledObject.simpleTestDefaultTagStatic(10); assertTrue( "Expected tag not found in " + listAppender.list.get(0).getMessage(), listAppender.list.get(0).getMessage().indexOf("tag[simpleTestDefaultTagStatic]") >= 0); new ProfiledObject().simpleTestUnprofiled(10); assertTrue( "Expected tag not found in " + listAppender.list.get(1).getMessage(), listAppender.list.get(1).getMessage().indexOf("tag[simpleTestUnprofiled]") >= 0); assertEquals("Expected two logging events", 2, listAppender.list.size()); }
private void initLogging(String location) throws JoranException { URL url = getResourceURL(location); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(url); }
public static void ConfigureLogbackDirectly(Context context) { // reset the default context (which may already have been initialized) // since we want to reconfigure it LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); // final String LOG_DIR = "/sdcard/GPSLogger"; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); final String LOG_DIR = prefs.getString( "gpslogger_folder", Environment.getExternalStorageDirectory() + "/GPSLogger"); GpsRollingFileAppender<ILoggingEvent> rollingFileAppender = new GpsRollingFileAppender<ILoggingEvent>(); rollingFileAppender.setAppend(true); rollingFileAppender.setContext(lc); // OPTIONAL: Set an active log file (separate from the rollover files). // If rollingPolicy.fileNamePattern already set, you don't need this. rollingFileAppender.setFile(LOG_DIR + "/debuglog.txt"); rollingFileAppender.setLazy(true); TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>(); rollingPolicy.setFileNamePattern(LOG_DIR + "/debuglog.%d.txt"); rollingPolicy.setMaxHistory(3); rollingPolicy.setParent(rollingFileAppender); // parent and context required! rollingPolicy.setContext(lc); rollingPolicy.start(); rollingFileAppender.setRollingPolicy(rollingPolicy); PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setPattern("%d{HH:mm:ss} %-5p %class{0}.%method:%L - %m%n"); encoder.setContext(lc); encoder.start(); rollingFileAppender.setEncoder(encoder); rollingFileAppender.start(); // setup LogcatAppender PatternLayoutEncoder encoder2 = new PatternLayoutEncoder(); encoder2.setContext(lc); encoder2.setPattern("%method:%L - %m%n"); encoder2.start(); LogcatAppender logcatAppender = new LogcatAppender(); logcatAppender.setContext(lc); logcatAppender.setEncoder(encoder2); logcatAppender.start(); // add the newly created appenders to the root logger; // qualify Logger to disambiguate from org.slf4j.Logger ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); root.addAppender(rollingFileAppender); root.addAppender(logcatAppender); }
@Before public void fixture() { lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); listAppender = new DummyLBAppender(); listAppender.setContext(lc); listAppender.start(); rootLogger = lc.getLogger("root"); rootLogger.addAppender(listAppender); }
private static void initLogback() throws JoranException { String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV)); // 初始化Logback LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); configurator.doConfigure(rocketmqHome + "/conf/logback_tools.xml"); }
@Before public void setUp() { // Silence all log messages from the PMS code that is being tested LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.reset(); // Initialize the RendererConfiguration RendererConfiguration.loadRendererConfigurations(); mediaInfoParserIsValid = MediaInfoParser.isValid(); }
/** 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); }
@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"); }
@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); } }
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."); }
/** * 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); // } }
@Override public void contextInitialized(ServletContextEvent sce) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); ClassPathResource resource = new ClassPathResource("logback-default.xml"); if (!resource.exists()) { String profile = EnvUtil.getProfile(); resource = new ClassPathResource("META-INF/logback/logback-" + profile + ".xml"); } configurator.doConfigure(resource.getInputStream()); logger.info("加载logback配置文件:" + resource.getURL().getPath()); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } StatusPrinter.printInCaseOfErrorsOrWarnings(context); }
public static void setLogConfig(String configFileName) throws Exception { ILoggerFactory fac = LoggerFactory.getILoggerFactory(); LoggerContext ctx = (LoggerContext) fac; System.out.println("LogFileSelector.setLogConfig() ctx received: " + ctx); JoranConfigurator cfg = new JoranConfigurator(); System.out.println("LogFileSelector.setLogConfig() JoranConfigurator created: " + cfg); cfg.setContext(ctx); System.out.println("LogFileSelector.setLogConfig() context was set."); ctx.reset(); System.out.println("LogFileSelector.setLogConfig() context was reset."); ClassLoader cl = LogFileSelector.class.getClassLoader(); InputStream in = cl.getResourceAsStream(configFileName); try { cfg.doConfigure(in); log.debug("---------------- log config changed to {}. ----------", configFileName); } catch (JoranException e) { throw new Exception("could not change log-config to " + configFileName, e); } }
public static void main(String[] args) { // assume SLF4J is bound to logback in the current environment LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); 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(); try { configurator.doConfigure(args[0]); } catch (JoranException e) { // StatusPrinter will handle this } logger.info("Entering application"); Foo foo = new Foo(); foo.doIt(); logger.info("Exiting application"); }
public static void main(String[] args) { Logger logger = (Logger) LoggerFactory.getLogger(JMSTopicAppenderTestApp.class); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); JMSTopicAppender appender = new JMSTopicAppender(); appender.setContext(lc); appender.setName("jmsTopic"); appender.setInitialContextFactoryName("org.apache.activemq.jndi.ActiveMQInitialContextFactory"); // appender.setPassword(""); appender.setProviderURL("tcp://localhost:61616"); // appender.setSecurityCredentials(""); // appender.setSecurityPrincipalName(""); appender.setTopicBindingName("MyTopic"); appender.setTopicConnectionFactoryBindingName("ConnectionFactory"); // appender.setURLPkgPrefixes(""); // appender.setUserName(""); appender.start(); logger.addAppender(appender); // JIT for (int i = 0; i < 10000; i++) { logger.debug("** Hello world. n=" + i); } long before = System.nanoTime(); for (int i = 0; i < 10000; i++) { logger.debug("** Hello world. n=" + i); } long after = System.nanoTime(); System.out.println("Time per logs for 10'000 logs: " + (after - before) / 10000); StatusPrinter.print(lc.getStatusManager()); }
private static void configureLogging(final Level consoleLevel, final Level fileLevel) { final LoggerContext loggerContext = LOG.getLoggerContext(); loggerContext.reset(); // set root log to the most permissive filter (affects performance big time (JAVACLI-90)) final int lowestLogLevel = Math.min(consoleLevel.toInt(), fileLevel.toInt()); LOG.setLevel(Level.toLevel(lowestLogLevel)); if (!consoleLevel.equals(Level.OFF)) { // create and add console appender final PatternLayoutEncoder consoleEncoder = new PatternLayoutEncoder(); consoleEncoder.setContext(loggerContext); consoleEncoder.setPattern(LOG_FORMAT_PATTERN); consoleEncoder.start(); final ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<ILoggingEvent>(); consoleAppender.setContext(loggerContext); consoleAppender.setName("STDOUT"); consoleAppender.setEncoder(consoleEncoder); final ThresholdFilter consoleFilter = new ThresholdFilter(); consoleFilter.setLevel(consoleLevel.levelStr); consoleFilter.setName(consoleLevel.levelStr); consoleFilter.start(); consoleAppender.addFilter(consoleFilter); consoleAppender.start(); LOG.addAppender(consoleAppender); } if (!fileLevel.equals(Level.OFF)) { // create file appender only if needed. // if done in the xml, it will create an empty file final RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>(); final FixedWindowRollingPolicy sizeBasedRollingPolicy = new FixedWindowRollingPolicy(); final SizeBasedTriggeringPolicy<Object> sizeBasedTriggeringPolicy = new SizeBasedTriggeringPolicy<Object>(); fileAppender.setContext(loggerContext); sizeBasedTriggeringPolicy.setContext(loggerContext); sizeBasedRollingPolicy.setContext(loggerContext); fileAppender.setRollingPolicy(sizeBasedRollingPolicy); sizeBasedRollingPolicy.setParent(fileAppender); sizeBasedRollingPolicy.setMinIndex(0); sizeBasedRollingPolicy.setMaxIndex(99); final Path logFilePath = FileSystems.getDefault().getPath(LOG_DIR, LOG_FILE_NAME); fileAppender.setFile(logFilePath.toString()); sizeBasedRollingPolicy.setFileNamePattern(LOG_DIR + LOG_ARCHIVE_FILE_PATTERN); sizeBasedRollingPolicy.start(); sizeBasedTriggeringPolicy.setMaxFileSize("10MB"); sizeBasedTriggeringPolicy.start(); final PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder(); fileEncoder.setContext(loggerContext); fileEncoder.setPattern(LOG_FORMAT_PATTERN); fileEncoder.start(); fileAppender.setTriggeringPolicy((TriggeringPolicy) sizeBasedTriggeringPolicy); fileAppender.setRollingPolicy(sizeBasedRollingPolicy); fileAppender.setEncoder(fileEncoder); fileAppender.setName("LOGFILE"); sizeBasedRollingPolicy.start(); final ThresholdFilter fileFilter = new ThresholdFilter(); fileFilter.setLevel(fileLevel.levelStr); fileFilter.setName(fileLevel.levelStr); fileFilter.start(); fileAppender.addFilter(fileFilter); LOG.addAppender((Appender) fileAppender); fileAppender.start(); } }
@Before public void resetLogging() { LoggerContext loggerContext = ((Logger) LoggerFactory.getLogger(getClass())).getLoggerContext(); loggerContext.reset(); BasicConfigurator.configure(loggerContext); }
@SuppressWarnings("unchecked") public static void main(String... args) throws ParseException, JoranException, IOException { Parser parser = new BasicParser(); CommandLine cl = null; try { cl = parser.parse(OPTS, args); } catch (ParseException e) { HelpFormatter help = new HelpFormatter(); help.printHelp("dlog", OPTS, true); System.exit(-1); } LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); loggerContext.reset(); if (cl.hasOption("config")) { // Read Logback configuration JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(loggerContext); configurator.doConfigure(cl.getOptionValue("file", "logback.xml")); StatusPrinter.printInCaseOfErrorsOrWarnings(loggerContext); } else { BasicConfigurator.configure(loggerContext); } Appender appender = null; if (cl.hasOption("output")) { String outputAppender = cl.getOptionValue("output", "console"); appender = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME).getAppender(outputAppender); } ChronicleTools.warmup(); Chronicle chronicle = new IndexedChronicle(cl.getOptionValue("path"), ChronicleConfig.DEFAULT); ExcerptTailer ex = chronicle.createTailer(); Level level = Level.valueOf(cl.getOptionValue("level", "TRACE")); if (cl.hasOption("head")) { int lines = Integer.parseInt(cl.getOptionValue("head", "10")); for (int i = 0; i < lines; i++) { LoggingEvent evt = readLoggingEvent(ex, loggerContext); if (evt.getLevel().isGreaterOrEqual(level)) { writeEvent(evt, appender); } } } else if (cl.hasOption("tail")) { int lines = Integer.parseInt(cl.getOptionValue("tail", "10")); Queue<LoggingEvent> tail = new LinkedBlockingQueue<LoggingEvent>(lines); while (ex.nextIndex()) { LoggingEvent evt = readLoggingEvent(ex, loggerContext); if (!tail.offer(evt)) { tail.poll(); tail.add(evt); } } LoggingEvent evt; while (null != (evt = tail.poll())) { if (evt.getLevel().isGreaterOrEqual(level)) { writeEvent(evt, appender); } } } else if (cl.hasOption("search")) { String regex = cl.getOptionValue("search"); Pattern regexPatt = Pattern.compile(regex); while (ex.nextIndex()) { LoggingEvent evt = readLoggingEvent(ex, loggerContext); if (null != evt && evt.getLevel().isGreaterOrEqual(level)) { if (regexPatt.matcher(evt.getFormattedMessage()).matches()) { writeEvent(evt, appender); } } } } loggerContext.stop(); chronicle.close(); }
@Test public void testNotifyOnReset() { context.reset(); assertEquals(UpdateType.RESET, listener.updateType); assertEquals(listener.context, context); }
public void stop() { reset(); fireOnStop(); resetAllListeners(); started = false; }
public void contextDestroyed(ServletContextEvent event) { ServletContext servletContext = event.getServletContext(); servletContext.log(LogbackConfigListener.class.getName() + ": Shutting down Logback"); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); lc.reset(); }